【发布时间】:2016-04-21 06:57:56
【问题描述】:
我正在 angular2 中创建高级登录系统。现在我面临拦截器问题。我在 angular2 中创建了用于 api 通信的网关。这是我的代码
gateWay(Method, Url, data) {
console.log("gateWay "+Method)
this.Method = Method
this.Url = Url
this.data = data
if(Method == "get"){
return this.http.get('http://localhost:3000/' + Url, { headers: this.insertAuthToken }).map((res) => res.json())
.map((res) => res.json())
}else if(Method == "post"){
return this.http.post('http://localhost:3000/' + Url, JSON.stringify(data), { headers: this.insertAuthToken })
.map((res) => res.json());
}else if(Method == "put"){
return this.http.put('http://localhost:3000/' + Url, JSON.stringify(data), { headers: this.insertAuthToken })
.map((res) => res.json());
}else if(Method == "delete"){
return this.http.delete('http://localhost:3000/' + Url, { headers: this.insertAuthToken })
.map((res) => res.json());
}
} 如果状态 200 意味着我可以在 console.log 中看到响应消息的状态代码。但是如果我得到 403 的响应意味着在这种情况下我需要处理一些功能,我面临的问题是我无法处理这些功能,因为我确实在我的组件中订阅了错误
this.httpService.gateWay('get', 'v1/users/index', undefined)
.subscribe(
data => console.log(data),
error => console.log(error),
() => console.log("finished")
)
所以如果我得到 403,请建议我一些触发功能的想法,否则例如 400 意味着需要在警报中显示消息。这是我的令牌设置,这里我使用 set Interval 重置令牌
SetTokenDynamically(time) {
console.log("time " + time)
clearInterval(this.timer)
this.timer = setInterval(() => {
// this.http.get('https://jsonblob.com/api/jsonBlob/56d80451e4b01190df528171')
this.http.get('http://localhost:3000/v1/users/tokenUpdate', { headers: this.headerRefreshToken })
.map((res) => res.json())
.subscribe(
data => {
Cookie.setCookie('Token2', data.token + this.a)
console.log("Call " + this.a)
this.response = data;
},
error => console.log(error),
() => {
console.log(this.response)
this.insertAuthToken = new Headers({
'AuthToken': this.response.token || ""
})
Cookie.setCookie('Authorization', this.response.token)
this.SetTokenDynamically(this.response.time_expiry_sec)
}
);
}, time);
}
【问题讨论】: