angular2 webapi调用async无法正常工作

时间:2017-03-27 15:30:47

标签: angularjs angular typescript asp.net-web-api

我有一个带有类和方法的角度2app,该方法执行web api调用然后在本地存储上设置一些项目,问题是因为它的ASYNC然后在下一行我没有本地存储值但是因为web api在那时没有返回任何信息。

如何确保在localstorage.getitem行之前成功返回了web api。

为简洁而减少了代码。

服务

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

组件

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

1 个答案:

答案 0 :(得分:1)

为了确保您拥有正确的信息,您不应该在您的服务中订阅,而是在您的组件中订阅:

服务

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

组件

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