您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

浅谈angular9中拦截器的用法

2025/7/5 4:05:57发布23次查看
本篇文章和大家一起聊聊angular9中拦截器的使用。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
相关教程推荐:《angular教程》
拦截器统一添加token
我们在做一个后台管理系统时,需要给每个请求的请求头里面添加token,所以下面我们来了解一下angular的拦截器,并使用
拦截器使用
1.创建http.service.ts,用于网络请求
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.创建noop.interceptor.ts,拦截器实现代码
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 {    // 拦截请求,给请求头添加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']);         })       );  }}
3.在app.module.ts中使用
3.1imports中引入httpclientmodule
3.2httpservice的注册
3.3noopinterceptor拦截器的使用
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 }   ],   // ... 省略})
拦截器实现后的效果
拦截器一般配合路由守卫一起使用。
更多编程相关知识,请访问:编程学习课程!!
以上就是浅谈angular9中拦截器的用法的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product