承诺并订阅

Promise and subscribe

我有一个 Angular2 (ionic2) 应用程序。我有一个请求城市的功能,但我得到一个错误,属性 subscribe does not exists on this.cityService.getAllCities().

cityPage.ts 有这样一个函数:

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

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

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

        });

    });

  }

编辑

根据评论,我更改了我的函数:

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!') 也没有被调用。

它抛出错误的原因,因为 .subscribe 方法在 Observable 上可用于监听,只要它发出数据。从 getAllCities 方法中,您正在 returning 一个 promise 您可以对其应用 .then 函数以从 return 中获取数据 Promise

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

而且 return 通过在 http.get() Observable 上调用 .toPromise() 方法从 getAllCities 方法承诺。

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