In front-end projects, we often need to do some unified processing of each request, such as the request results session expired processing, the header head with validation parameters token and so on, this time need to use the interceptor.
Due to HTTP requests in angular, dependent on the @angular/common/http module, objects such as httpinterceptor,httprequest,httpresponse are introduced into
Import { httpinterceptor, HttpRequest, HttpHandler, httperrorresponse, httpheaderresponse, HttpResponse,} from ' @angular/common/http ';
After introducing the module, we want to implement the Httpinterceptor interface
Export class Myinterceptor implements Httpinterceptor { constructor () {}}
Specific interceptors are partially implemented:
Intercept (REQUEST:HTTPREQUEST<ANY>, Next:httphandler): observable< | Httpheaderresponse | Httpresponse<any> > {
Let req = Request.clone ({param1: ', param2: '});//You can add the parameter return Next.handle (req) in the request. Pipe (Mergemap (Event:any) = = { //normal return, handling specific return parameters if (event instanceof httpresponse && event.status = = =) return This.handledata (event);//Specific processing request returns data return of (event); }), Catcherror ((err:httperrorresponse) = This.handledata (Err)) }
In common our business often return 200, but there may be business errors, such as the wrong parameters of the request, the session expires without validation, etc., this time we need to do a unified processing
Private Handledata ( event:httpresponse<any> | Httperrorresponse, ): observable<any> { //Business process: Some general operations switch (event.status) {case : if (event instanceof HttpResponse) { const Body:any = event.body; if (body && body.rc = = 3) { This.goto ('/test ');} } break; Case 401://Not logged in status Code this.goto ('/login '); break; Case 404: Case: ... break; Default: Return of (event); }
Here we have the same unified processing of the different return states.
Finally, we introduce the Interceptor module into the App.module.ts module. Basically, it's done.
Import {Myinterceptor} from './myintercept ' @NgModule ({ ... Providers: [{provide:http_interceptors, Useclass:myinterceptor, Multi: true}] ...})
Note: This part of the code refers to the ng-alain of the interceptor, if you want to understand can refer to Https://github.com/cipchk/ng-alain
ANGULAR6 http request blocker