我最近升级到 Angular 4,并希望能够在用户有401
响应时从服务中重定向用户。 我无法注射NavController
或Nav
所以我无法使其工作。
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(public auth: AuthProvider, private global: GlobalVariablesProvider) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("401 working")
return next.handle(request).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
}
}, (err: any) => {
console.log(err)
if (err instanceof HttpErrorResponse) {
console.log(err)
if (err.status === 401) {
this.global.handleResponse("Unathorized attempt. Redirecting to login")
// Perform redirect
}
}
});
}
}
我想我需要访问全球nav
但我不确定该怎么做。
我能够导入App
并调用getRootNav()
:
import { App } from "ionic-angular"
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(public auth: AuthProvider, public app: App, private global: GlobalVariablesProvider) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
}
}, (err: any) => {
console.log(err)
if (err instanceof HttpErrorResponse) {
console.log(err)
if (err.status === 401) {
this.global.handleResponse("Unauthorized attempt. Redirecting to login")
this.app.getRootNav().setRoot(LoginPage)
}
}
});
}
}