如何从角度5中的httpIntercepter重定向到登录页面

时间:2017-12-19 17:21:34

标签: angular ionic-framework

我已经在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

                    }
                }
            });
    }
}

由于

看起来没有办法在Intercepter中注入NavController。 这是我发现的。

https://github.com/ionic-team/ionic/issues/13026

1 个答案:

答案 0 :(得分:1)

您可以尝试注入App

constructor(private injector: Injector,
            public appCtrl: App) {
}

然后将其用于导航目的:

this.appCtrl.getRootNavs()[0].setRoot('LoginPage')

this.appCtrl.getRootNavs()[0].push('LoginPage')