3

My Service class contains code as :

Service.ts

//all imports are done
@Injectable()
export class Service{


    constructor(private http: Http) { }

    getGoogle():Observable<any> {
        console.log("Inside service");
        return this.http.get('https://jsonplaceholder.typicode.com/posts/1');
    }
}

My page component where I make use of service.

Page.ts

//all imports are done

export class Page1{

constructor(private service: Service, private navCtrl: NavController) { }


 async get() {
    console.log("inside get method");
    const data =  await this.service.getGoogle().toPromise();
      console.log('The response is' , data);
       }

}

I have got the required result, but as to understand the concept of Observables and Observer, my Observable should have an Observer sitting to subscribe.Then why should'nt the code const data = await this.service.getGoogle.subscribe().toPromise() does not work here and shows error that property toPromise() does not exists on type Subscription.

I saw the official resource of toPromise() where I found that it is used with .just().toPromise().Then I found .just() API which states that

The just() method emits its parameter(s) as OnNext notifications, and after that, it emits an OnCompleted notification.

So It is using the features of subscribe here then why it is not used with .subscribe()?

cartant
  • 57,105
  • 17
  • 163
  • 197
user8348978
  • 81
  • 1
  • 1
  • 7
  • Because `toPromise` is callable on an `Observable` - not a `Subscription` - and `toPromise` performs the subscription. – cartant Jul 24 '17 at 06:47
  • Also, the link in your question references the RxJS 4 docs. The RxJS 5 - which is what's used in Angular - docs are [here](http://reactivex.io/rxjs/). – cartant Jul 24 '17 at 07:21

1 Answers1

4

To get the values from an observable, you'll subscribe() on the observable. This starts the observable and it will send you the values it produces.

If you rather want to use a Promise you can call toPromise() on the observable instead. This will make the observable behave like a regular promise.

Under the covers, toPromise() calls subscribe() on the observable and waits for it to send complete(). When the complete() signal is received, the promise will resolve the last emitted next() signal.

toPromise() looks a bit like this:

myObservable.takeLast().subscribe(value => resolve(value));
Jon G Stødle
  • 3,844
  • 1
  • 16
  • 22