我有一个使用刷新令牌的Ionic 3应用程序。 问题是当生成新的访问令牌时,不会更新视图。 另一种情况是,当方案是服务器的更新时,请求不再执行。
Angular: 5.2.7
RxJS: 5.5.6
我进入了一些使用switchMap()
的代码,但是由于异步函数总是返回Promise<>
,所以我无法使用它。
我尝试了以下代码:
[AppHttpInterceptor.ts]
constructor(private event: Events, private authService: AuthService,
private refreshTokenService: RefreshTokenService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("intercepted request ... ", req.url);
return next.handle(req)
.catch(error => {
if (!error.ok && error.error.error === 'invalid_grant') {
console.log('Logout');
this.event.publish('logout');
}
if (req.url != AUTH_ENDPOINT) {
if (error instanceof HttpErrorResponse) {
if (error.status !== 401)
return Observable.throw(error);
return this.authService
.refreshToken()
.then(response => {
console.log('Response: ', response);
console.log('Retrying ... ', req.url);
this.refreshTokenService.publish(''); // Added to each view to make them refresh the data =(.
return next.handle(req);
}).catch((err: any) => {
console.log('Logout');
this.authService.logout();
return Observable.throw(error);
});
}
}
}) as any;
}
[auth.service.ts]
constructor(private http: HttpClient, private storage) { }
public async refreshToken() {
await this.storage.get('userAuth')
.then(userAuth => { this.userAuth = userAuth });
let params = await this.GetAuthRefreshParams(this.userAuth);
let body = await this.encodeParams(params);
return await this.http.post(this.authUrl, body).toPromise()
.then((res: any) => {
if (typeof res.access_token !== 'undefined') {
this.userLogin = this.GetAuthResponse(res);
this.userLogin.RefreshToken = this.userAuth.RefreshToken; // Keeps the old refresh token.
//.
//. Set AuthStorage and GetUserData...
//.
return this.userLogin;
}
}).catch(error => {
console.log(error);
return Observable.throw(error);
});
}
我要实现的是在重试请求后刷新视图,而不在每个页面上添加观察者; 即使在向服务器发送添加/更新时也重试请求。