RequestOptions Angular 5 Migration

I used custom query parameters in Angular 4, where I did the following:

default-Request-options.service.ts

@Injectable() export class DefaultRequestOptions extends BaseRequestOptions { headers = new Headers({ 'Accept': 'application/json', 'Content-Type': 'application/json' }); merge(options?: RequestOptionsArgs): RequestOptions { var newOptions = super.merge(options); const token: string = localStorage.getItem('token'); if (token) { newOptions.headers.set('token', token); } return newOptions; } } 

App.Module.ts

 providers: [ // expose our Services and Providers into Angular dependency injection { provide: RequestOptions, useClass: DefaultRequestOptions } ] 

But after the migration notification that RequestOption is not available in the new http / common / http folder

I would like to know if I can use a similar thing in Angular 5 or does it make sense to use it with the new HTTPClient? The main advantage for me was to install in only one place, without adding it to all my requests.

First I got the code in Angular docs: https://github.com/angular/angular.io/blob/master/public/docs/_examples/server-communication/ts/src/app/default-request-options.service. ts

+5
source share
1 answer

You can use interceptors to add default headers to your requests. Example from angular docs:

 import {Injectable} from '@angular/core'; import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http'; @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor(private auth: AuthService) {} intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // Get the auth header from the service. const authHeader = this.auth.getAuthorizationHeader(); // Clone the request to add the new header. const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)}); // Pass on the cloned request instead of the original request. return next.handle(authReq); } } 
+5
source

Source: https://habr.com/ru/post/1273781/


All Articles