Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise and subscribe

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 has a function like this:

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

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

        });

    });

  }

Edit

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

        });

    });

  }

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.

like image 688
kwv84 Avatar asked Apr 24 '17 19:04

kwv84


People also ask

What is difference between Promise and subscribe?

Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time. Emit multiple values over a period of time. Emit a single value at a time. Are lazy: they're not executed until we subscribe to them using the subscribe() method.

Can we subscribe to a Promise?

A Promise object serves as a link between the executor (the “producing code” or “singer”) and the consuming functions (the “fans”), which will receive the result or error. Consuming functions can be registered (subscribed) using the methods . then and . catch .

What's the difference between the Promise and Observable?

the Promise is always asynchronous, while the Observable can be either asynchronous or synchronous, the Promise can provide a single value, whereas the Observable is a stream of values (from 0 to multiple values), you can apply RxJS operators to the Observable to get a new tailored stream.


1 Answers

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);
            });
        });
    });
}
like image 186
Pankaj Parkar Avatar answered Sep 24 '22 07:09

Pankaj Parkar