如何将此数据从提供程序中的promise返回到组件

时间:2018-04-25 04:29:06

标签: angular typescript

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

getLocations位于provider

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

我对angular很新,这是我第一次使用component/provider/promise进行HTTP调用。

非常感谢任何帮助/建议。

这是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;
}

3 个答案:

答案 0 :(得分:0)

首先,您需要解决承诺中的数据,如下所示:

// Promise provide two executors for normal and exception branches
new Promise(resolve, reject)

// if you are using HttpClient instead of Http, you don't need to call .json method
resolve(res.json());  
// for throwing err
reject(new Error('sample err'))  

然后,您可以在承诺的then中获取结果数据,如下所示:

this.loginProvider.getLocations().then(result => {
  // result is the data you resolved in promise
  // do things based on result 
}).catch(err => {
  // deal with exceptions
})

有关承诺的更多信息,请参阅 docs

答案 1 :(得分:0)

当您已经使用toPromise()调用时,我不相信您需要明确创建新的承诺。 我会用这样的东西:

async ngOnInit(): Promise<void> {
   this.locations = await this._getLocations();
}

private _getLocations(): Promise<Location[]> {
   return this._http.get<LocationReturnData>(apiUrl).toPromise().then(res => res);
}

async和await只是处理承诺的简写。 await将在转到下一行代码之前等待promise的返回,它需要异步处理程序。它更短更短比堆叠更简单()&#39; s。

我没有注意到http的注入,但我假设您正在使用最新的HttpClient,默认情况下应该为您处理任何json数据。

答案 2 :(得分:0)

如果在其他方法调用中需要请求的结果,则应在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
            }
        );
    }
}