如何在同一个控制器中调用一个函数

问题描述 投票:0回答:2

如何在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();

enter image description here

angular typescript ionic2
2个回答
1
投票

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

ngOnInit() {
    this.initialiseWeight();
}

1
投票

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

ngOnInit(){
   this.initialiseWeight();
}

要么

someFunctionName(){
   this.initialiseWeight();
}
© www.soinside.com 2019 - 2024. All rights reserved.