Notes for a front-end developer, esyou.net

0%

ANGULAR4-HTTP拦截器

http拦截器的使用主要用于http请求,比如设置http请求头,常用于header中包含token或者cookie,以及设置请求方式为 application/x-www-form-urlencoded 或 application/json等,也可以对请求的api进行拦截。

在angular4中使用 @angular/common/http进行http请求,来做拦截器,相关代码如下:

InterceptorService.ts(此处为ionic3框架使用的方法,angular4 WEB请看下一个实例代码)

1
// http 请求拦截器
2
import { Injectable } from '@angular/core'
3
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http'
4
import { Observable } from 'rxjs'
5
import { catchError } from 'rxjs/operators'
6
import { _throw } from 'rxjs/observable/throw'
7
import { NativeStorage } from '@ionic-native/native-storage'
8
import { Utils } from './utils'
9
10
@Injectable()
11
export class InterceptorService implements HttpInterceptor{
12
    private timeout = 1000 * 30 // 30s超时
13
    private timer = 0
14
    constructor(
15
        private utils: Utils,
16
        private storage: NativeStorage){}
17
    intercept(request: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
18
        // 排除不需要进行token验证的接口
19
        let excludeUrl = ['login', 'logout']
20
        let isNotVerifyToken = false
21
        excludeUrl.map(item => {
22
            if(request.url.indexOf(item) > -1) {
23
                isNotVerifyToken = true
24
            }
25
        })
26
        if(!isNotVerifyToken){
27
            // 此处使用promise的方式获取localstorage
28
            let token = localstorage.getItem('token')
29
            let cloneRequst = this.addToken(request, token)
30
            return next.handle(cloneRequst).timeout(this.timeout).pipe(
31
            // 异常集中处理,只要请求有error就直接返回网络错误+状态code
32
               catchError(error => {
33
                  // 简单的防抖,防止多次执行提示网络错误
34
                  clearTimeout(this.timer)
35
                  this.timer = setTimeout(() => {
36
                      let msg = '网络错误'
37
                      alert(msg)
38
                  }, 2000)
39
                  return _throw(error)
40
               })
41
             )
42
           })
43
        }else {
44
            let cloneRequst = this.addToken(request)
45
            return next.handle(cloneRequst).timeout(this.timeout).pipe(
46
                // 异常集中处理,只要请求有error就直接返回网络错误+状态code
47
                catchError(error => {
48
                    // 简单的防抖,防止多次执行提示网络错误
49
                    clearTimeout(this.timer)
50
                    this.timer = setTimeout(() => {
51
                        let msg = '网络错误'
52
                        alert(msg)
53
                    }, 2000)
54
                    return _throw(error)
55
                })
56
            )
57
        }
58
    }
59
60
    private addToken(request: HttpRequest<any>, token?: any) {
61
        let req: HttpRequest<any>
62
        if(token) {
63
            req = request.clone({
64
                // 拦截所有请求,并且在header中增加响应头以及token
65
                setHeaders: {
66
                    'Accept': 'application/json',
67
                    'Content-Type': 'application/x-www-form-urlencoded',
68
                    'Authorization': token
69
                }
70
            })
71
        }else {
72
            // 当页面不需要在header中传递token时设置header
73
            req = request.clone({
74
                setHeaders: {
75
                    'Accept': 'application/json',
76
                    'Content-Type': 'application/x-www-form-urlencoded'
77
                }
78
            })
79
        }
80
        return req
81
    }
82
}

app.modules.ts

1
//import部分加入以下代码
2
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
3
//@NgModule部分providers最后加入如下代码
4
{provide: HTTP_INTERCEPTORS, useClass: InterceptorService, multi: true}

直接使用如下代码进行http请求即可

1
this.http.post(url, body).subscribe(data => {
2
    if(data) {
3
        return data
4
    }else {
5
        return null
6
    }
7
  }, err => {
8
    return err
9
})