Home  >  Article  >  Web Front-end  >  A brief discussion on the usage of interceptors in angular9

A brief discussion on the usage of interceptors in angular9

青灯夜游
青灯夜游forward
2021-01-29 19:10:062523browse

This article will talk with you about the use of interceptors in angular9. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

A brief discussion on the usage of interceptors in angular9

Related tutorial recommendations: "angular tutorial"

Interceptors uniformly add token

When we are building a backend management system, we need to add a token 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')
  }}

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>> {
    // 拦截请求,给请求头添加token
    let url = req.url // 可以对url进行处理
    let token = document.cookie && document.cookie.split("=")[1]
    // 登录请求排除在外
    // if (!url.includes('login')) {
        req = req.clone({
            url, // 处理后的url,再赋值给req
            headers: req.headers.set('Authorization', 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(['/login']);
         })
       );
  }}</httpevent></any>

3. Use

3.1Introduce HttpClientModule## in app.module.ts

#3.2 Registration of HttpService

3.3 Use of NoopInterceptor interceptor

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';import { HttpService } from './auth/http.service';import { NoopInterceptor } from './auth/noop.interceptor';@NgModule({
   imports: [
      BrowserModule,
      HttpClientModule,
      AppRoutingModule   ],
   providers: [
      HttpService,
      { provide: HTTP_INTERCEPTORS, useClass: NoopInterceptor, multi: true }
   ],
   // ... 省略})

The effect after the interceptor is implemented

A brief discussion on the usage of interceptors in angular9 Interceptors are generally used together with routing guards.

For more programming-related knowledge, please visit:

Programming Learning Course! !

The above is the detailed content of A brief discussion on the usage of interceptors in angular9. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete