这篇文章主要介绍angular9中拦截器怎么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
拦截器统一添加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 }
],
// ... 省略})
拦截器实现后的效果
拦截器一般配合路由守卫一起使用。
以上是“angular9中拦截器怎么用”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注天达云行业资讯频道!