我想在http请求401错误上重定向到登录页面。我如何在IONIC 3中实现它。由于IONIC 3使用Angular 4,这就是为什么我不能在HTTP拦截器中使用任何服务。
答案 0 :(得分:6)
@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)