2

I am working on Angular4. I have something that I don't undestand. I store a value on the service provider and then I get it from a component. This is my code:

gard service provider:

key:any;
constructor(){}
    storeKeysAppPreferences(res){
            this.appPreferences.clearAll();
            console.log("storeKeysAppPreferences",res);
            this.appPreferences.store('key1',JSON.stringify(res));
        }

        fetchKeysAppPreferences(){
          this.appPreferences.fetch("key1").then(
            (res) => {
                this.key=(JSON.parse(res));
              }
           );
        }

When I try console.log()

fetchKeysAppPreferences(){
  this.appPreferences.fetch("key1").then(
    (res) => {
        this.key.push(JSON.parse(res));
        console.log(this.key); //is definded
      }
   );
   console.log(this.key); // undefined
}

the value of key is undefined. Why is that?

Sampath
  • 63,341
  • 64
  • 307
  • 441
Hamdy
  • 430
  • 1
  • 6
  • 19
  • Calm down man, there's no `http` word in it. It could be a custom classe that has the same keywords. OP, what does your `appPreferences` class does ? is it making http calls, or local storage calls, or ... ? –  Nov 22 '17 at 13:39
  • the app references is basically a file that we store on it data like tokens – Hamdy Nov 22 '17 at 13:40
  • @trichetriche It is a duplicate regardless of whether there is `http` in the code or not. The callback of a promise `then` call is asynchronous by definition. – str Nov 22 '17 at 13:41

2 Answers2

1

Since it is async operation you need to do like below:

Note: Here it shows just the concept only.Please arrange methods according to your use case.

constructor(){}
    storeKeysAppPreferences(res){
            this.appPreferences.clearAll();
            console.log("storeKeysAppPreferences",res);
            this.appPreferences.store('key1',JSON.stringify(res)).then(()=>{//here is the place
                  fetchKeysAppPreferences(){
                      this.appPreferences.fetch("key1").then(
                         (res) => {
                            this.key=(JSON.parse(res));
                          }
                      );
                    }
                    })
          }
Sampath
  • 63,341
  • 64
  • 307
  • 441
  • The storeKeysAppPreferences and fetchKeysAppPreferences are two separate methods. I call storeKeysAppPreferences on the login page and I call fetchKeysAppPreferences on the homepage. So I can not do it like that – Hamdy Nov 22 '17 at 13:47
  • I just showed the concept only. This seems to be an issue of Async pattern. So I would like to suggest you to send data using `push/setRoot` method. – Sampath Nov 22 '17 at 14:05
0

You have to put console.log(this.key); // undefined inside the callback indeed the second console.log() is executed before the response is ready.

Danilo Dughetti
  • 1,360
  • 1
  • 11
  • 18