How do I set the baseUrl for Angular HttpClient?

后端 未结 6 1878
甜味超标
甜味超标 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 07:05

    Why not create an HttpClient subclass that has a configurable baseUrl? That way if your application needs to communicate with multiple services you can either use a different subclass for each, or create multiple instances of a single subclass each with a different configuration.

    @Injectable()
    export class ApiHttpClient extends HttpClient {
      public baseUrl: string;
    
      public constructor(handler: HttpHandler) {
        super(handler);
    
        // Get base url from wherever you like, or provision ApiHttpClient in your AppComponent or some other high level
        // component and set the baseUrl there.
        this.baseUrl = '/api/';
      }
    
      public get(url: string, options?: Object): Observable {
        url = this.baseUrl + url;
        return super.get(url, options);
      }
    }
    

提交回复
热议问题