0

How to call a function within the same controller in Angular 2, because this gives me an error:

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

3
  • Can you please post the full function? You're probably missing a brace somewhere. Did you mean to call that function recursively by the way? Commented Sep 1, 2018 at 12:08
  • Yes I just added the full function. No I don't mean it to call it recursively, it is an initialization function, I want to call it at start only. Commented Sep 1, 2018 at 12:15
  • So where do you want to call it from? ngOnInit? Commented Sep 1, 2018 at 12:17

2 Answers 2

1

You can't call a piece of code within a method so you should call this.initialiseWeight() inside another method, for exemple:

ngOnInit() {
    this.initialiseWeight();
}
Sign up to request clarification or add additional context in comments.

Comments

1

you should call this.initialiseWeight(); in ngOnInit() for initialization purposes or you can call it from another function someFunction()

ngOnInit(){
   this.initialiseWeight();
}

or

someFunctionName(){
   this.initialiseWeight();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.