2017-12-19 12 views
1

Ionic 3/angular 5でカスタムauthinterterpterを構築しました。 AuthInterceptでトークンが不正ではあるがログインにリダイレクトする方法が見つからない場合、ログインページにリダイレクトしたいページ。角度5のhttpIntercepterからログインページにリダイレクトする方法

@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

+0

他の場所からナビゲートするのと同じように、インターセプタにルータサービスを注入し、router.navigate()を呼び出します。 –

+0

@JBNizet私はイオン通信のルータサービスを持っていませんが、navControllerを持っています。私はNavControllerを注入しようとしましたが動作しませんでした。 –

+0

あなたが試したことを示し、あなたが期待したことを説明し、代わりに何をしたのかを説明してください。正確に。 –

答えて

0

あなたはAppを注入しようとすることができます。その後、

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

そして、このようなナビゲーションのためにそれを使用する:

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

または

this.appCtrl.getRootNavs()[0].push('LoginPage') 
関連する問題