2 ionic3
我想重定向到http请求401错误的登录页面.我如何在IONIC 3中实现它.由于IONIC 3使用Angular 4,这就是为什么我不能在HTTP Interceptor中使用任何服务.
那么你可以这样做.
@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.
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
现在,抓住你的活动app.component.ts.
this.event.subscribe('UNAUTHORIZED', () => {
if (this.rootPage != LoginComponent) {
this.rootPage = LoginComponent;
}
});
Run Code Online (Sandbox Code Playgroud)
你也可以像导入appCtrl那样做.
this.appCtrl.getRootNavs()[0].setRoot(LoginComponent)
Run Code Online (Sandbox Code Playgroud)