Promise and subscribe

后端 未结 1 441
-上瘾入骨i
-上瘾入骨i 2021-01-02 17:41

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.getAllCit

相关标签:
1条回答
  • 2021-01-02 18:42

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

    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);
                });
            });
        });
    }
    
    0 讨论(0)
提交回复
热议问题