如何设置Angular HttpClient的baseUrl? [英] How do I set the baseUrl for Angular HttpClient?

查看:580
本文介绍了如何设置Angular HttpClient的baseUrl?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有在文档中找到一种方法来设置HTTP请求的基本API URL.可以使用Angular HttpClient做到这一点吗?

I did not find a way in the documentation to set the base API URL for HTTP requests. Is it possible to do this with the Angular HttpClient?

推荐答案

使用新的HttpClient拦截器.

Use the new HttpClient Interceptor.

创建实现HttpInterceptor的适当注射剂:

Create a proper injectable that implements HttpInterceptor:

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class APIInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const apiReq = req.clone({ url: `your-api-url/${req.url}` });
    return next.handle(apiReq);
  }
}

HttpInterceptor可以克隆请求并根据需要更改它,在这种情况下,我为所有http请求定义了默认路径.

The HttpInterceptor can clone the request and change it as you wish, in this case I defined a default path for all of the http requests.

为HttpClientModule提供以下配置:

providers: [{
      provide: HTTP_INTERCEPTORS,
      useClass: APIInterceptor,
      multi: true,
    }
  ]

现在,您的所有请求都将以your-api-url/

Now all your requests will start with your-api-url/

这篇关于如何设置Angular HttpClient的baseUrl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆