【发布时间】:2019-07-16 00:16:53
【问题描述】:
这几个小时我一直在摸不着头脑,我希望有人可以帮助我并指导我。所以,我正在开发一个 Angular 7 应用程序身份验证模块。要求之一是开发 HTTP 拦截器以添加授权 (JWT) 令牌并处理所有错误消息。
我正在使用 NPM 包来处理令牌的本地存储。这个包使用 set 和 get 方法来存储和返回一个 promise 而不是令牌的实际值。
现在,我的问题在于我的拦截器功能,如下所示。我试图评论我卡住的地方。
intercept(request: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
// Trying to get the token here but this returns a promise
// this.token is a service for managing storage and retrieving of tokens
const token = this.token.getToken();
// If token is got, set it in the header
// But when i console log, i see [object promise] other than the token
if (token) {
request = request.clone({
headers: request.headers.set('Authorization', 'Bearer ' + token)
});
}
return next.handle(request).pipe(catchError(err => {
// Logs out the user if 401 error
if (err.status === 401) {
this.token.remove()
.then(() => {
this.auth.changeAuthStatus(false);
this.router.navigateByUrl('/login');
});
}
// Returns the error message for the user to see
// for example in an alert
const error = err.error.message || err.statusText;
return throwError(error);
}));
}
我希望我已经很好地解释了这个问题。我曾尝试在拦截器函数之前使用async,但我得到一个红色的讨厌的错误,说TS1055: Type 'typeof Observable' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value. Types of parameters 'subscribe' and 'executor' are incompatible.。
对于解决此问题的任何帮助,我将不胜感激。
谢谢!
【问题讨论】:
-
你把token存到localstorage了吗?
-
@ZarnaBorda 我实际上正在使用 ionic,我想坚持使用默认返回承诺的存储包。我设法使用下面的废弃代码解决了这个问题。
标签: angular angular7 angular-http-interceptors