How do I set the baseUrl for Angular HttpClient?

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

    Based on TheUnreal's very useful answer, the interceptor can be written to get the base url through DI:

    @Injectable()
    export class BaseUrlInterceptor implements HttpInterceptor {
    
        constructor(
            @Inject('BASE_API_URL') private baseUrl: string) {
        }
    
        intercept(request: HttpRequest, next: HttpHandler): Observable> {
    
            const apiReq = request.clone({ url: `${this.baseUrl}/${request.url}` });
            return next.handle(apiReq);
        }
    }
    

    BASE_API_URL can be provided by the application module:

    providers: [
        { provide: "BASE_API_URL", useValue: environment.apiUrl }
    ]
    

    where environment is the object automatically created by the CLI when generating the project:

    export const environment = {
      production: false,
      apiUrl: "..."
    }; 
    

提交回复
热议问题