ANGULAR4---Authentication---Use httpclient interceptors to solve cyclic dependency reference problems

Source: Internet
Author: User

In the ANGULAR4 project, header information Accesstoken as the credential for authentication is required for each request server. But it becomes cumbersome to write code to add a header message every time the server is called. You can use ANGULAR4 's httpclient to intercept each request, and then add information to the header.

Directly on the code practice

First, create the Interceptor service, implement the intercept method of Httpinterceptor

Import {injectable, Injector} from '@angular/core'; import {httpevent, HttpHandler, Httpinterceptor, HttpRequest, HttpResponse} from '@angular/common/http'; import {Observable} from 'rxjs/observable'; Import'rxjs/add/operator/do'; import {authenticationservice} from './auth/authentication.service';//service class for obtaining AccesstokenImport {Environment} from '.. /.. /environments/environment';/** * http blocker, set header information*/@Injectable () exportclassBasehttpinterceptorservice implements Httpinterceptor {authservice:authenticationservice; Skipauth: [string]; Constructor (Privateinject:injector) {  //User Login or authentication request does not need to add header Accesstoken information     This. Skipauth =[' ${environment.serverurl}/api/v1/user/login ',]; }  /** * Interceptor Interception Request * @param {httprequest<any>} req * @param {HttpHandler} next * @returns {Observable*/Intercept (Req:httprequest<any>, Next:httphandler): observable {     This. Authservice = This. Inject.Get(AuthenticationService); //Note this sentence Constreq_started =Date.now ();    Let Authreq; /** * If you skip the certified link, do not add header information*/    if( This. Isskipauth (Req.url)) {Authreq=Req.clone (); }Else {      ConstAccess_token = ' Bearer ${ This. Authservice.getaccesstoken ('[email protected]')}`; Authreq=Req.clone ({setheaders: {Authorization:access_token}}); }    returnNext.handle (Authreq). Do(Event= {      if(Eventinstanceof HttpResponse) {        Constelapsed = Date.now ()-req_started; Console.log (' Request for${req.urlwithparams} took ${elapsed} MS ');  }    }); }  /** Whether to skip adding header authentication*/isskipauth (URL:string) {Let IsMatch=false;  This. Skipauth.foreach (Reg_url:string) = {      if( !IsMatch) {        if(Url.search (Reg_url) >=0) {IsMatch=true;    }      }    }); returnIsMatch; }}

Second, register the Interceptor, in the Appmodule, add the following code

{      provide:http_interceptors,      useclass:basehttpinterceptorservice,//  The interceptor name defined above       true    },

Third, each request server data service relies on httpclient, not http.

Then a basic interceptor has been completed, but you will notice an error when invoking the service of authentication services:Cyclic dependency error with Httpinterceptor, If you add the first step of the code to the attention point of the code, you will find OK again.

This is a dependency injection loop nesting: a relies on b,b and references a.

ForwardRef is used in official documents , but found useless. It was seen in stack overflow that the above method was used to solve the problem successfully. https://github.com/angular/angular/issues/18224

If you need more detailed code or have a problem, please contact me

ANGULAR4---Authentication---Use httpclient interceptors to solve cyclic dependency reference problems

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.