我有一个拦截器,它可以在令牌过期时捕获服务器错误。然后拦截器向api请求刷新的令牌。如果成功,拦截器将再次发送http请求。出错时,拦截器会删除本地存储,并应重定向到登录页面。
现在我有了一个带有canDeactivate守卫的页面。所以我想在canDeactivate保护中检查token是否有效。如果无效,我想向API请求一个刷新的令牌。在成功的时候,我不想离开页面。在错误时,我想注销用户,并重定向到登录页面。
// canDeactivateGuard
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
@Injectable({
providedIn: 'root',
})
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate) {
return component.canDeactivate ? component.canDeactivate() : true;
}
}// component
canDeactivate(): Observable<boolean> | boolean {
if (!this.authService.isTokenValid()) {
// here i want to ask the api for a new token
// on error of api I want to redirect the user to login page
// and don't want to show a modal
return this.authService.refreshToken().pipe(
map(res => {
console.log('test');
return false;
}),
catchError(err => {
console.log('test error');
return of(true);
})
);
}
if (Object.is(this.testForm.get('text').value, this.oldText)) {
this.modalService.hide(1);
return true;
} else {
this.modalRef = this.modalService.show(this.modalTemplate);
return false;
}
}// AuthService
public refreshToken(): Observable<Token> {
return this.http.post<{ data: any }>(`${environment.apiUrl}/auth/refresh`, {}).pipe(
map(({ data }): any => {
const apiToken = this.tokenAdapter.adapt(data);
this.setJwtToken(apiToken);
this.currentTokenSubject.next(apiToken);
return apiToken;
})
);
}我不知道如何更改从api捕获错误的代码,以及如何重定向用户。未调用canDeactivate方法的map()和catchError()中的console.logs。
发布于 2019-07-03 16:51:02
refreshToken应该遵循下面的格式,这会很有帮助
return this.http.get(`${environment.apiUrl}/auth/refresh`, {
}).pipe(
map(({ data }): any => {
const apiToken = this.tokenAdapter.adapt(data);
this.setJwtToken(apiToken);
this.currentTokenSubject.next(apiToken);
return apiToken;
}),
catchError(() => {
return of(false);
}));然后在canDeactivate方法中
// component
canDeactivate(): Observable<boolean> | boolean {
if(!this.authService.isTokenValid()) {
// here i want to ask the api for a new token
// on error of api I want to redirect the user to login page
// and don't want to show a modal
return this.authService.refreshToken().pipe(
map(res => {
if (!res) {
console.log('test error');
return true;
}
console.log('test');
return false;
})
);
}
if (Object.is(this.testForm.get('text').value, this.oldText)) {
this.modalService.hide(1);
return true;
} else {
this.modalRef = this.modalService.show(this.modalTemplate);
return false;
}
}https://stackoverflow.com/questions/56865231
复制相似问题