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

后端 未结 7 1474
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:19

    After release of Angular 4.3 we have a possibility to use HttpClient interceprtors. The advantage of this method is avoiding of import/injection of API_URL is all services with api calls.

    This is my basic implementation:

    @Injectable()
    export class ApiUrlInterceptor implements HttpInterceptor {
    constructor(@Inject(API_URL) private apiUrl: string) {}
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        req = req.clone({url: this.prepareUrl(req.url)});
        return next.handle(req);
      }
    
      private isAbsoluteUrl(url: string): boolean {
        const absolutePattern = /^https?:\/\//i;
        return absolutePattern.test(url);
      }
    
      private prepareUrl(url: string): string {
        url = this.isAbsoluteUrl(url) ? url : this.apiUrl + '/' + url;
        return url.replace(/([^:]\/)\/+/g, '$1');
      }
    }
    

    InjectionToken declaration:

    export const API_URL = new InjectionToken<string>('apiUrl');
    

    Provider registration:

    {provide: API_URL, useValue: environment.apiUrl}
    {provide: HTTP_INTERCEPTORS, useClass: ApiUrlInterceptor, multi: true, deps: [API_URL]}
    

    Environment.ts:

    export const environment = {
     production: false,
     apiUrl: 'some-dev-api'
    };
    
    0 讨论(0)
提交回复
热议问题