How to Append Base URL to HTTP requests?
We can append base URL to HTTP requests using –
1. Dependency Injection
2. Using HttpInterceptors
The following example for append base URL using DI -
Firstly, we register a base URL provider in the NgModule and after register this BASE_URL, it is available universally in your Apps.
//Runtime or injector configuration
//providers is used for runtime injector configuration.
providers: [{ provide: 'BASE_URL', useFactory: getBaseUrl }],
Now provide factory method which gets the base URL from <base> element.
export function getBaseUrl() {
return document.getElementsByTagName('base')[0].href;
}
Finally, we can get the base URL injected and add it to URL-
export class GetUserComponent {
constructor(http: Http, @Inject('BASE_URL') baseUrl: string) {
http.get(baseUrl + 'api/users').subscribe(data => {
this.users = data.json();
}, error => console.error(error));
}
}
The following example for append base URL using HttpInterceptors –
If we wants to create an interceptor, we must create an Injectable class which implements HttpInterceptor.
Firstly, register interceptor in the module provider -
//Runtime or injector configuration
//providers is used for runtime injector configuration.
providers: [{ provide: HTTP_INTERCEPTORS, useClass: ApiInterceptor, multi: true } ],
And after register interceptor, to create –
@Injectable()
export class ApiInterceptor implements HttpInterceptor {
//Intercepts HttpRequest and handles them.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const baseUrl = document.getElementsByTagName('base')[0].href;
const apiReq = req.clone({ url: `${baseUrl}${req.url}` });
return next.handle(apiReq);
}
}
Now we can access the base URL in your across apps.
For
more detail kindly refer the link - https://www.code-sample.com/2018/05/angular-5-6-7-routing-and-navigation.html