Why don't we need to subscribe to an observable here before converting it to a Promise?

Viewed 207

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()?

1 Answers
Related