How to store the root url of api in angular 4 app?

后端 未结 7 1476
Happy的楠姐
Happy的楠姐 2020-12-29 03:16

I followed the official tutorials and made services for the Apis but absolute url of the Api is hardcoded in services.

I want to keep the base url of Api somewhere s

7条回答
  •  甜味超标
    2020-12-29 04:02

    You can create an Interceptor to add the base API URL

    @Injectable()
    export class CustomHttpInterceptor implements HttpInterceptor {
    
      intercept(request: HttpRequest, next: HttpHandler): Observable> {
        console.log('Custom Interceptor');
    
        // Adding serverHostURL to all APIs in Interceptor
        const serverHostURL = 'http://localhost:8080';
        request = request.clone({
          url: serverHostURL + request.url
        });
    
    
        return next.handle(request);
      }
    

    Above code should do.

提交回复
热议问题