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
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'
};