简体   繁体   中英

angular2 webapi call async not working

I have an angular 2app with a class and a method, the method executes a web api call and then sets some items on local storage, the problem is that because its ASYNC then on the next line I dont have the local storage values yet because the web api hasnt returned any info at that point.

How can I make sure that the web api has been succesfully returned before the localstorage.getitem line.

Code reduced for brevity.

Service

 login(email) {
        let params: URLSearchParams = new URLSearchParams();
        params.set('email', email);

        //Header
        let headers = new Headers({
            'Content-Type': AppSettings.ContentType,
            'Authorization': AppSettings.Authorization + localStorage.getItem("AccessToken"),
            'X-Developer-Id': AppSettings.XDeveloperId,
            'X-Api-Key': AppSettings.XApiKey
        });

        var RequestOptions: RequestOptionsArgs = {
            url: AppSettings.UrlLoginPatient,
            method: 'GET',
            search: params,
            headers: headers,
            body: null
        };

        this.http.get(AppSettings.UrlLoginPatient, RequestOptions)
            .map(res => res.json())
            .subscribe(
            data => { this.saveData(data, email); },
            err => this.Error(err)
            );
    }

    saveData(data, email) {
        localStorage.setItem('patientId', data.data.patientId);
        localStorage.setItem('emailLogin', email);
    }

    Error(err) {
        console.log('error: ' + err);
    }

Component

LoginApp() {

    this.login.login('a@com.com');

    if (localStorage.getItem("patientId") != null) {
      this.navCtrl.push(AttentionTypePage);
    } else {
      let alert = this.alertCtrl.create({
        subTitle: 'El correo electrónico no ha sido encontrado.',
        buttons: ['Intentar nuevamente']
      });
      alert.present();
    }
  }

To ensure that you have the right informations, you shouldn't subscribe in your service but in your component :

Service

login(email) {
  //do stuff with headers, and request options
  return this.http.get(AppSettings.UrlLoginPatient, RequestOptions)
    .map(res => res.json())
    .do(data => this.saveData(data, email));
}

Component

LoginApp() {
  this.login.login('a@com.com').do(data => {
    if (localStorage.getItem("patientId") != null) {
      this.navCtrl.push(AttentionTypePage);
    } else {
      let alert = this.alertCtrl.create({
        subTitle: 'El correo electrónico no ha sido encontrado.',
        buttons: ['Intentar nuevamente']
      });
      alert.present();
    }
  }).subscribe();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM