1

I am storing a user id in the storage and trying to get the stored id when the page is loaded.

Below is the code snippet

constructor(
  private nav: NavController, 
  private auth: AuthService,
  public clockservice: ClockService,
  private alertCtrl: AlertController,
  private loadingCtrl: LoadingController,
  public storage: Storage
) {

  storage.get('name').then(val => {
    this.username = val; 
  })

  storage.get('id').then(val => {
    this.userid = val;     
    console.log(this.userid);
  })
}

ngOnInit() {    
  console.log("inside");
  console.log(this.userid); 
  getStatus();
}

getStatus() {
  this.showLoading();
  this.clockservice.getinoutstatus(this.userid).subscribe(
    result => {
      if (result.success) {
        // do something here
      } else {
        this.showError("API Error.");
      }
      this.loading.dismiss();
    },
    error => {
      this.showError("API Error.");
    }
  );
}

The issue I face is the user id is not received in the ngOnInit event. The console log shows the ngOnInit is called even before the user id is received in the constructor.

console log:

inside

1

How to make sure that is ngOnInit even is called after all the get values received in the constructor?

cartant
  • 57,105
  • 17
  • 163
  • 197
arun kumar
  • 703
  • 2
  • 13
  • 33
  • The promises in the constructor have nothing to do with `ngOnInit` and the assignments made to the member properties will not occur until the storage promises resolve. – cartant Jan 22 '17 at 03:57
  • I need to make a http post in the ngOnInit based on the user id. How do I call the http post after the storage.get('id') promise is resolved. Can I put inside then ? – arun kumar Jan 22 '17 at 08:42
  • If you include your HTTP call in your question, it will be easier to give you an answer. – cartant Jan 22 '17 at 08:46
  • Included actual code. The getstatus always show API error because empty user id passed to the service. – arun kumar Jan 22 '17 at 08:55
  • @arun kumar I changed my answer. can you test it. – amin arghavani Jan 22 '17 at 10:39

1 Answers1

1

The simplest solution would be to perform a Promise.all to wait for both storage values to be retrieved and to then call getStatus:

ngOnInit() {
  Promise.all([
    this.storage.get('name'),
    this.storage.get('id')
  ])
  .then(([name, id]) => {
    this.username = name;
    this.userid = id;
    getStatus();
  })
  .catch(error => {
    this.showError("Storage Error.");
  });
}

Retrieving the storage values in the constructor would be okay, but - looking at the implementation - it seems likely that getStatus should not be called before ngOnInit. So move the storage calls and the promise chain into ngOnInit

cartant
  • 57,105
  • 17
  • 163
  • 197
  • It seems right solution. It shows the following error during build. Type 'any[]' is not assignable to type 'string'. this.username = name; – arun kumar Jan 22 '17 at 09:51