Home Web Front-end JS Tutorial A brief discussion on the usage of interceptors in angular9

A brief discussion on the usage of interceptors in angular9

Jan 29, 2021 pm 07:10 PM
Interceptor

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

1

2

3

4

5

6

7

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

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>

Copy after login

3. Use

3.1Introduce HttpClientModule## in app.module.ts

#3.2 Registration of HttpService

3.3 Use of NoopInterceptor interceptor

1

2

3

4

5

6

7

8

9

10

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 }

   ],

   // ... 省略})

Copy after login

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 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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Demystifying the interceptor mechanism in Golang Demystifying the interceptor mechanism in Golang Apr 08, 2024 am 08:39 AM

Interceptor is a design pattern that allows custom behavior to be inserted before and after method execution. In Go, it can be implemented through net/http middleware. It has the advantages of scalability, reusability, testability, etc., and can be used in scenarios such as authentication, authorization, caching, logging, and custom error handling.

Tips for using route interceptors in uniapp Tips for using route interceptors in uniapp Dec 17, 2023 pm 04:30 PM

Tips for using route interceptors in uniapp In uniapp development, route interceptors are a very common function. Route interceptors allow us to perform some specific operations before routing jumps, such as permission verification, page passing parameters, etc. In this article, we will introduce the tips for using route interceptors in uniapp and provide specific code examples. Create a route interceptor First, we need to create a route interceptor in the uniapp project. The creation method is as follows: Create an inter in the project root directory

Understand the principles and advantages of Spring interceptors Understand the principles and advantages of Spring interceptors Dec 30, 2023 pm 12:25 PM

Explore the working principle and advantages of Spring interceptor Introduction: The Spring framework is one of the most commonly used frameworks in Java development. It provides rich functions and flexibility, allowing developers to develop applications more efficiently. One of the important components is the interceptor. This article will delve into the working principles and advantages of Spring interceptors and give specific code examples. 1. How Spring interceptor works Spring interceptor uses aspect-oriented programming (

Comprehensive analysis of interceptors in Golang Comprehensive analysis of interceptors in Golang Apr 07, 2024 am 10:18 AM

In Golang, interceptors can be used to insert additional code before and after function execution. The scenarios include logging, authentication, caching, etc. Interceptors are implemented by creating a handler function type and then creating the interceptor function that accepts the handler function and returns a new handler function that contains additional logic. In actual combat, we can use interceptors to record all requests to facilitate debugging and analysis.

Mastering interceptors in Golang Mastering interceptors in Golang Apr 07, 2024 pm 09:33 PM

Interceptors allow custom logic to be inserted into Go applications without modifying existing code. They can be used for authentication, logging, error handling, performance monitoring, etc. Creating an interceptor requires implementing the Handler interface, which defines the ServeHTTP() method for processing HTTP requests and the Next() method for passing control. Practical examples show how to use logging interceptors to log the URL paths of all incoming requests, and how to chain multiple interceptors (such as authentication interceptors) together to create complex application logic.

Does golang have an interceptor? Does golang have an interceptor? Jul 18, 2023 pm 02:23 PM

Golang does not provide a built-in interceptor, but you can use language features such as functions, interfaces, and structures to achieve similar functions. The following are commonly used interceptor implementation methods: 1. Functional interceptor, by processing the request before it reaches the handler and its Then call the function to implement the interceptor; 2. Interface interceptor, implement the interceptor by defining an interface and implementing the interface before and after the target handler. This method can make the interceptor more flexible and can be used in different situations. Implement different interceptor logic on the interface.

In-depth analysis: the practical application effect of Golang interceptor In-depth analysis: the practical application effect of Golang interceptor Mar 21, 2024 am 09:18 AM

Golang interceptor is a powerful design pattern that can implement many functions in practical applications, such as logging, error handling, permission control, etc. This article will deeply analyze the actual application effect of Golang interceptor, and demonstrate its usage and effect through specific code examples. 1. What is Golang interceptor? Golang interceptor is an aspect-oriented programming (AOP) design pattern. By adding a layer of proxy before and after function calls, you can intercept and intercept functions.

How to handle the interception and unified processing of network requests in Vue technology development How to handle the interception and unified processing of network requests in Vue technology development Oct 08, 2023 am 09:11 AM

How to handle the interception and unified processing of network requests in Vue technology development. As a popular front-end development framework, Vue can easily make network requests through its built-in axios library. In actual development, we often need to intercept and uniformly process network requests to implement some common functions, such as authentication, error handling, etc. This article will introduce how to intercept and uniformly process network requests in Vue development, and provide specific code examples. 1. The concept and function of interceptors. Before introducing the specific processing methods, let’s first

See all articles