本文摘自PHP中文网,作者青灯夜游,侵删。

相关教程推荐:《angular教程》
拦截器统一添加token
我们在做一个后台管理系统时,需要给每个请求的请求头里面添加token,所以下面我们来了解一下angular的拦截器,并使用
拦截器使用
1.创建http.service.ts,用于网络请求
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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,拦截器实现代码
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 32 33 34 35 36 37 38 39 40 41 42 | 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' ;
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
constructor (private router: Router) {}
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
let url = req.url
let token = document.cookie && document.cookie.split( "=" )[1]
req = req.clone({
url,
headers: req.headers.set( 'Authorization' , token)
})
return next.handle(req).pipe(
tap(
event => {
if (event instanceof HttpResponse) {
console.log(event);
if (event.status >= 500) {
}
}
},
error => {
})
);
}
}
|
3.在app.module.ts中使用
3.1imports中引入HttpClientModule
3.2HttpService的注册
3.3NoopInterceptor拦截器的使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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)
更多编程相关知识,可访问:编程入门!!
以上就是如何使用angular9拦截器?的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
如何使用angular9拦截器?
更多相关阅读请进入《angular9拦截器的使用》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » 如何使用angular9拦截器?