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

查看:56
本文介绍了如何为 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天全站免登陆