承诺并订阅 [英] Promise and subscribe

查看:21
本文介绍了承诺并订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Angular2 (ionic2) 应用程序.我有一个请求城市的函数,但我收到一个错误消息:this.cityService.getAllCities() 上不存在属性订阅.

I have an Angular2 (ionic2) application. I have a function that request cities but I get an error that Property subscribe does not exists on this.cityService.getAllCities().

cityPage.ts 有这样的功能:

cityPage.ts has a function like this:

getCities(){
    this.cityService.getAllCities()
          .subscribe(cityData => { this.cityList = cityData; },
            err => console.log(err),
            () => console.log('Complete!')
    );
}

我的 cityService.getAllCities() 函数如下所示:

my cityService.getAllCities() function looks like this:

getAllCities(){

    return new Promise (resolve => {
        this.storage.ready().then(() => {

            this.storage.get('authData').then(authData => {
              let hdr = new Headers({'Content-Type': 'application/json', 'Authorization': 'Bearer ' +
                authData.access_token });
              let opt = new RequestOptions({ headers: hdr });
                return this.http.get(AppSettings.API_GET_CITIES).map(res => <CityModel[]> res.json(), opt);
            }).catch(() => {
              //resolve(false);
            });

        });

    });

  }

编辑

根据评论,我改变了我的功能:

Based on the comment I've changed my function like this:

getAllCities(){

    return Observable.create(resolve => {
        this.storage.ready().then(() => {

            this.storage.get('authData').then(authData => {
              let hdr = new Headers({'Content-Type': 'application/json', 'Authorization': 'Bearer ' +
                authData.access_token });

                console.log('access_token ' + authData.access_token);
              let opt = new RequestOptions({ headers: hdr });
                 return this.http.get(AppSettings.API_GET_CITIES,opt).map(res => <CityModel[]> res.json()).subscribe((result) => {
                  console.log(result);
                  resolve = result;
                });
            }).catch(() => {
              //resolve(false);
            });

        });

    });

  }

在我的 console.log(result) 中,我收到数据,但数据从未返回到我的 getCities() 函数.也没有调用 console.log('Complete!').

In my console.log(result) I receive data, but the data is never returned to my getCities() function. Also the console.log('Complete!') is not called.

推荐答案

之所以抛出错误,是因为 .subscribe 方法确实可以在 Observable 上监听, 每当它发出数据.这里从 getAllCities 方法返回一个 promise 你可以应用 .then 函数来获取从 Promise<返回的数据/代码>

The reason it is throwing an error, because .subscribe method does available on Observable to listen to, whenever it emits a data. Here from getAllCities method you're returning a promise you could apply .then function over it to get data returned from that Promise

getCities() {
  this.cityService.getAllCities()
    .then(
       cityData => { this.cityList = cityData; },
       err => console.log(err),
       () => console.log('Complete!')
  );
}

并且还通过在 http.get() Observable 上调用 .toPromise() 方法从 getAllCities 方法返回承诺.

And also return promise from getAllCities method by calling .toPromise() method over http.get() Observable.

getAllCities(){

    return new Promise (resolve => {
        this.storage.ready().then(() => {

            this.storage.get('authData').then(authData => {
              let hdr = new Headers({'Content-Type': 'application/json', 'Authorization': 'Bearer ' +
                authData.access_token });
              let opt = new RequestOptions({ headers: hdr });
              //returned promise from here.
                return this.http.get(AppSettings.API_GET_CITIES)
                   .map(res => <CityModel[]> res.json(), opt)
                   .toPromise();
            }).catch(() => {
              //resolve(false);
            });
        });
    });
}

这篇关于承诺并订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆