我想在 http 请求 401 错误时重定向到登录页面。我如何在 IONIC 3 中实现它。由于 IONIC 3 使用 Angular 4,这就是我不能在 HTTP 拦截器中使用任何服务的原因。
最佳答案
你可以这样做。
@Injectable()
export class Httpinterceptor implements HttpInterceptor {
private _inProgressCount = 0;
constructor(private event: Events) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone();
return next
.handle(authReq)
.do((ev: HttpEvent<any>) => {
if (ev instanceof HttpResponse) {
//HTTP Response
}
}, (err: any) => {
/* HTTP ERRORRESPONSE goes here */
// you can catch your http error here
if (err.status == 401) {
this.event.publish('UNAUTHORIZED'); // catch the published event in app.component.ts where you define your rootPage.
}
});
}
}
现在,在您的 app.component.ts
中捕获事件。
this.event.subscribe('UNAUTHORIZED', () => {
if (this.rootPage != LoginComponent) {
this.rootPage = LoginComponent;
}
});
您也可以采用其他方式,例如导入 appCtrl。
this.appCtrl.getRootNavs()[0].setRoot(LoginComponent)
关于ionic3 - 如何在 IONIC 3 的 Http 拦截器中使用 NavControl?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49644167/