Home > Web Front-end > JS Tutorial > How to use angular9 interceptor?

How to use angular9 interceptor?

青灯夜游
Release: 2020-09-12 11:13:15
forward
4184 people have browsed it

How to use angular9 interceptor?

Related tutorial recommendations: "angular tutorial"

Interceptors uniformly add token

When we are building a background management system, we need to add tokens to the request header of each request, so let’s learn about angular’s ​​interceptor and use

Interceptor usage

1. Create http.service.ts for network requests

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class HttpService {

  constructor(private http: HttpClient) { }
  getData () {
    return this.http.get('/assets/mock/data.json')
  }
}
Copy after login

2. Create noop. interceptor.ts, interceptor implementation code

import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse
} from '@angular/common/http';

import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { Router } from '@angular/router';

/** Pass untouched request through to the next request handler. */
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
    constructor (private router: Router) {}
  intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpEvent<any>> {
    // 拦截请求,给请求头添加token
    let url = req.url // 可以对url进行处理
    let token = document.cookie && document.cookie.split("=")[1]
    // 登录请求排除在外
    // if (!url.includes(&#39;login&#39;)) {
        req = req.clone({
            url, // 处理后的url,再赋值给req
            headers: req.headers.set(&#39;Authorization&#39;, token)//请求头统一添加token
        })
    // }
    return next.handle(req).pipe(
        tap(
         event => {
          if (event instanceof HttpResponse) {
           console.log(event);
           if (event.status >= 500) {
            // 处理错误
           }
          }
         },
         error => {
          // token过期 服务器错误等处理
        //   this.router.navigate([&#39;/login&#39;]);
         })
       );
  }
}
Copy after login

3. Use

in app.module.ts and introduce HttpClientModule

## in imports #3.2HttpService registration

3.3The use of NoopInterceptor interceptor

import { HttpClientModule, HTTP_INTERCEPTORS } from &#39;@angular/common/http&#39;;
import { HttpService } from &#39;./auth/http.service&#39;;
import { NoopInterceptor } from &#39;./auth/noop.interceptor&#39;;
@NgModule({
   imports: [
      BrowserModule,
      HttpClientModule,
      AppRoutingModule
   ],
   providers: [
      HttpService,
      { provide: HTTP_INTERCEPTORS, useClass: NoopInterceptor, multi: true }
   ],
   // ... 省略
})
Copy after login
The effect after the interceptor is implemented

How to use angular9 interceptor?

Interceptors generally cooperate with routing Guards are used together. If you want to know more, you can read another article, routing guards (https://blog.csdn.net/qq_44855897/article/details/106985343)


Reference materials

1. Angular official website (https://angular.cn/guide/http#intercepting-requests-and-responses)

2. Code address (https://github.com/zhuye1993/angular9-route)

For more programming-related knowledge, please visit:

Introduction to Programming! !

The above is the detailed content of How to use angular9 interceptor?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template