[英]How to redirect to login page from httpIntercepter in angular 5
I've built custom authIntercepter in Ionic 3 / angular 5. I wanna redirect to login page if token unauthorized in AuthIntercept but can't find a way to redirect to login page. 我已经在Ionic 3 / angular 5中构建了自定义authIntercepter。如果在AuthIntercept中未经授权令牌但我无法找到重定向到登录页面的方法,我想重定向到登录页面。
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
private authService: AuthService;
constructor(private injector: Injector) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const started = Date.now();
this.authService = this.injector.get(AuthService);
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.authService.accessToken}`,
'Content-Type': 'application/json'
}
});
return next
.handle(request)
.do(event => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
const elapsed = Date.now() - started;
console.log(`Request for ${request.urlWithParams} took ${elapsed} ms.`);
}
}, err => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
// redirect to the login route
}
}
});
}
}
Thanks 谢谢
Looks like there is no way to inject NavController in Intercepter. 看起来没有办法在Intercepter中注入NavController。 Here is what I found, though.
不过这是我发现的。
https://github.com/ionic-team/ionic/issues/13026 https://github.com/ionic-team/ionic/issues/13026
You can try to inject the App
: 您可以尝试注入
App
:
constructor(private injector: Injector,
public appCtrl: App) {
}
And then to use it for navigation purposes like this: 然后将其用于导航目的,如下所示:
this.appCtrl.getRootNavs()[0].setRoot('LoginPage')
or 要么
this.appCtrl.getRootNavs()[0].push('LoginPage')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.