尝试在提供程序内部使用ionic 3时出现navCtrl问题

时间:2019-07-09 09:44:51

标签: angular typescript ionic-framework ionic3 angular6

我正在尝试使用户的令牌过期时导航至登录页面。关键是在令牌拦截器提供程序内部,它在“执行以下操作”下面显示红线:

  return next.handle(_req).do((event: HttpEvent<any>) => {

,也位于navCtrl的这一行下:

this.navCtrl.push('LoginPage');

这是完整的代码:

import { switchMap } from 'rxjs/operators';
import { TokenProvider } from './token/token';
import { Observable } from 'rxjs/Observable';
import { fromPromise } from 'rxjs/observable/fromPromise';
import { Injectable } from '@angular/core';
import {
  HttpInterceptor,
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpResponse,
  HttpErrorResponse
} from '@angular/common/http';
import {
  IonicPage,
  NavController,
  NavParams,
  AlertController,
  LoadingController
} from 'ionic-angular';


@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(private tokenProvider: TokenProvider) {}

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return fromPromise(this.tokenProvider.GetToken()).pipe(
      switchMap(token => {
        const headersConfig = {
          'Content-Type': 'application/json',
          Accept: 'application/json'
        };
        if (token) {
          headersConfig['Authorization'] = `beader ${token}`;
        }
        const _req = req.clone({ setHeaders: headersConfig });
        return next.handle(_req).do((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        // do stuff with response if you want
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        if (err.status === 401) {
          this.navCtrl.push('LoginPage');
          // or show a modal
        }
      }
    });
      })
    );
  }
}

怎么了?如何解决这两个问题?

1 个答案:

答案 0 :(得分:0)

您正在使用this.navCtrl。在此之前,我们需要导入NavController。就像链接(https://ionicframework.com/docs/v3/api/navigation/NavController/

import { NavController } from 'ionic-angular';

class MyComponent {
  constructor(public navCtrl: NavController) {

  }
  service(){
  this.navCtrl.push('MyPage');
  }
}