承诺和订阅

时间:2017-04-24 19:47:42

标签: angular ionic2 angular2-services

我有一个Angular2(ionic2)应用程序。我有一个请求城市的函数,但我收到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!')未被调用。

1 个答案:

答案 0 :(得分:7)

它抛出错误的原因,因为.subscribe方法在Observable上可用于侦听,只要它发出数据。在getAllCities方法中,您返回promise,您可以对其应用.then函数,以便从Promise

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

并通过getAllCities方法调用.toPromise()方法,从http.get()方法返回承诺。

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