百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>JS教程> 怎样使用angular9拦截器?
分享文章到:

怎样使用angular9拦截器?

发布时间:09/01 来源:未知 浏览: 关键词:

拦截器统一增加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<HttpEvent<any>> {
    // 拦截恳求,给恳求头增加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 }
   ],
   // ... 省略
})

拦截器实现后的结果

在这里插入图片描述

拦截器一样配合路由保卫一起使用,想理解可以看另一遍文章,路由保卫(https://blog.csdn.net/qq_44855897/article/details/106985343)

参照 材料

1、angular官网(https://angular.cn/guide/http#intercepting-requests-and-responses)
2、代码地址(https://github.com/zhuye1993/angular9-route)

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有159人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板