【问题标题】:How to call a function within the same controller如何在同一个控制器中调用函数
【发布时间】:2019-02-07 05:21:27
【问题描述】:

如何在 Angular 2 中调用同一控制器中的函数,因为这会给我一个错误:

initialiseWeight(){
    this.storage.ready().then(() => {
        return this.storage.get('weightunit');
    })
    .then(retrievedUnit => {
        if (retrievedUnit) {
            this.data.weightunit = retrievedUnit;
        } else {
            this.data.weightunit = 'kg';
            this.storage.set('weightunit', this.data.weightunit);
        }
    })
    .catch(e =>  console.error('ERROR: could not read Storage Weight, error:', e));

    this.storage.ready().then(() => {
        return this.storage.get('realWeight');
    })
    .then(retrievedRealWeight => {
        if (retrievedRealWeight && retrievedRealWeight!== "0" ) {
            this.data.realWeight = parseInt(retrievedRealWeight, 10);
            this.storage.get('userWeight').then((value) => {
                this.data.userWeight = parseInt(value, 10);
              });
             if ( (this.data.realWeight * 1.02 < this.data.userWeight) && (!this.data.isWetsuit) ) {
                this.data.userWeight = this.data.realWeight;
                this.storage.set('userWeight', this.data.userWeight);
            }
        } else {
            this.data.realWeight = 70;
            this.data.userWeight = 70;
            this.storage.set('realWeight', this.data.realWeight);
            this.storage.set('userWeight', this.data.userWeight);
        }
    })
    .catch(e =>  console.error('ERROR: could not read Storage Weight, error:', e));
}
this.initialiseWeight();

【问题讨论】:

  • 你能发布完整的功能吗?您可能在某处缺少支架。顺便说一句,您的意思是递归调用该函数吗?
  • 是的,我刚刚添加了完整的功能。不,我不是要递归调用它,它是一个初始化函数,我只想在开始时调用它。
  • 那么你想从哪里调用它? ngOnInit?

标签: angular typescript ionic2


【解决方案1】:

你不能在一个方法中调用一段代码,所以你应该在另一个方法中调用this.initialiseWeight(),例如:

ngOnInit() {
    this.initialiseWeight();
}

【讨论】:

    【解决方案2】:

    您应该在ngOnInit() 中调用this.initialiseWeight(); 进行初始化,或者您可以从另一个函数someFunction() 调用它

    ngOnInit(){
       this.initialiseWeight();
    }
    

    someFunctionName(){
       this.initialiseWeight();
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-16
      • 2015-02-06
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多