首页 > 解决方案 > 如何从提供者中的承诺将此数据返回到组件

问题描述

下面的代码显示了我在组件中的调用。

getLocations是在provider.

我无法理解如何将数据返回到组件以显示给用户。我可以在控制台中看到格式的数据,[{},{}]但需要在前端访问使用它。

我对 Angular 很陌生,这是我第一次尝试使用component/provider/promise.

任何帮助/建议将不胜感激。

这是 Angular 5 的最佳实践吗?对不起我的无知。

constructor(public navCtrl: NavController, public navParams: NavParams, public loginProvider: LoginProvider, public alertCtrl: AlertController) {

        this.loginProvider.getLocations();
  }

getLocations() {
    let promise = new Promise((resolve, reject) => {
      let apiURL = 'http://xxxx-dev.xxxxxxx.com/api/default/v1/locations';
       this.http.get(apiURL)
      .toPromise()
      .then(
        res => { // Success

          this.locations = res.json(); 
          console.log(this.locations);
          resolve();                

        }
      );
  });
  return promise;
}

标签: angulartypescript

解决方案


如果您在其他方法调用中需要请求的结果,您应该在 onfulfilled(success) 函数中返回它,如下所示:

    getLocations() {
         let apiURL = 'http://xxxx-dev.xxxxxxx.com/api/default/v1/locations';
         return   this.http.get(apiURL)
          .toPromise()
          .then(
            (success) => { 
              this.locations = res.json(); 
              console.log(this.locations);

              return success;          
            }
          );
    }

    otherMethod() {
        getLocations().then(
            (res) => {
                //you see result of query that returned in http request
            }
        );
    }
}

推荐阅读