首页 文章

TypeError:无法读取 Ionic 2 中未定义的属性'viewCtrl'

提问于
浏览
0

我从一个特定页面调用的提供程序中有一个Observable.timer。我还将一个函数传递给提供者 Observable,当它完成倒计时时,它将调用位于初始页面中的函数。但是在计时器结束后我收到错误:

注意:我在页面内导入了 View Controller 但没有提供者(如果我尝试在提供程序中导入 View Controller,我会收到另一个错误)

错误

取消订阅时发生 1 errors:↵1)TypeError:无法读取未定义的属性'viewCtrl'

newTimer() {
    this.countDown = this.timerProvider.newTimer(this.endTimer); //pass function below
  }

  endTimer() {

    const indexModal = self.viewCtrl.index;
    // then we remove it from the navigation stack
    //this.navCtrl.remove(2);

    self.navCtrl.push(WinnersPage, {
      gameId: self.gameId
    }).then(() => {

    });

    console.log('timer ENDED');
  }

**** PROVIDER

countDown: any;
  counter = 1*100;
  tick = 1000;

  constructor(public http: HttpClient) {
    //console.log('Hello TimerProvider Provider');
  }

  newTimer(endTimer) {
     return Observable.timer(0, this.tick)
      .take(this.counter).map(() => --this.counter)
      .finally(() => endTimer());
  }

1 回答

  • 0

    你可以使用简单,

    newTimer() {
        this.countDown = this.timerProvider.newTimer(this.endTimer.bind(this)); 
      }
    

    要么:

    由于你从another function调用function,****的引用在endTimer funciton中不可用

    所以,将component this分配给global variable self并在endTimer function中使用它

    试试这个,

    let self = this;
    
      newTimer() {
        this.countDown = this.timerProvider.newTimer(this.endTimer); //pass function below
      }
    
      endTimer() {
    
        const indexModal = self.viewCtrl.index;
        if(self.answerModal) {
          self.answerModal.dismiss();
        }
        if(self.hintModal) {
          self.hintModal.dismiss();
        }
        self.navCtrl.push(WinnersPage, {
          gameId: self.gameId
        }).then(() => {
    
        });
    
        self.storage.set('firstAnswerCreated', '');
        self.playaudio.pause();
    
        console.log('timer ENDED');
      }
    

相关问题