简体   繁体   English

angular2 webapi调用异步不起作用

[英]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. 我有一个带有类和方法的angular 2app,该方法执行Web api调用,然后在本地存储上设置一些项目,问题在于,由于其ASYNC然后在下一行中,我还没有本地存储值,因为Web api尚未返回任何信息。

How can I make sure that the web api has been succesfully returned before the localstorage.getitem line. 如何确保在localstorage.getitem行之前成功返回了Web api。

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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