How do I set the baseUrl for Angular HttpClient?

后端 未结 6 1883
甜味超标
甜味超标 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:10

    you don't necessarily need a base URL with HttpClient, the docs says you just have to specify the api part of the request, if you are making calls to the same server it is straightforward like this:

    this.http.get('/api/items').subscribe(data => { ...

    However, you can if you need or want to, specify a base URL.

    I have 2 suggestions for doing that:

    1. A helper class with a static class property.

    export class HttpClientHelper{
    
        static baseURL: string = 'http://localhost:8080/myApp';
    }
    
    
    this.http.get(`${HttpClientHelper.baseURL}/api/items`);//in your service class
    

    2. A base class with a class property so any new service should extend it:

    export class BackendBaseService {
    
      baseURL: string = 'http://localhost:8080/myApp';
    
      constructor(){}
    

    }

    @Injectable()
    export class ItemsService extends BackendBaseService{
    
      constructor(private http: HttpClient){  
        super();
      }
    
      public listAll(): Observable{    
        return this.http.get(`${this.baseURL}/api/items`);
      }
    
    }
    

提交回复
热议问题