How do I set the baseUrl for Angular HttpClient?

后端 未结 6 1880
甜味超标
甜味超标 2021-01-30 06:21

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?

6条回答
  •  不思量自难忘°
    2021-01-30 06:50

    Use the new HttpClient Interceptor.

    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, next: HttpHandler): Observable> {
    
        const apiReq = req.clone({ url: `your-api-url/${req.url}` });
        return next.handle(apiReq);
      }
    }
    

    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.

    Provide the HttpClientModule with the following configurations:

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

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

提交回复
热议问题