Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the baseUrl for Angular HttpClient?

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?

like image 751
Stepan Suvorov Avatar asked Aug 17 '17 12:08

Stepan Suvorov


People also ask

How do you define the base URL in post call?

The base URL contains the account id (a.k.a. Munchkin id) and is therefore unique for each Marketo subscription. Your base URL is found by logging into Marketo and navigating to the Admin > Integration > Web Services menu.

What is observe in HttpClient?

Observe Response HttpClient object allows accessing complete response, including headers. In the browser, response body is a JSON object, which can be copied to a typescript interface or class type.

Why is HttpClient return observable?

In general, an observable can return multiple values over time. An observable from HttpClient always emits a single value and then completes, never to emit again. Which is indeed true, Http request/response can't produce any more values once the request completes.

What is BASE HREF in Angular?

The <base href="/"> tells the Angular router what is the static part of the URL. The router then only modifies the remaining part of the URL. Without the base href tag you will see errors like this: Angular 2 Router no Base href set.


Video Answer


1 Answers

Use the new HttpClient Interceptor.

Create a proper injectable that implements HttpInterceptor:

import {Injectable} from '@angular/core'; import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http'; import {Observable} from 'rxjs/Observable';  @Injectable() export class APIInterceptor implements HttpInterceptor {   intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {      const apiReq = req.clone({ url: `your-api-url/${req.url}` });     return next.handle(apiReq);   } } 

The HttpInterceptor can clone the request and change it as you wish, in this case I defined a default path for all of the http requests.

Provide the HttpClientModule with the following configurations:

providers: [{       provide: HTTP_INTERCEPTORS,       useClass: APIInterceptor,       multi: true,     }   ] 

Now all your requests will start with your-api-url/

like image 155
TheUnreal Avatar answered Sep 30 '22 10:09

TheUnreal