Property 'subscribe' does not exist on type 'Promise'

Viewed 31198

I'm still confused about how rxjs works.

I am building an Ionic app that makes a request to my server and expects json. I have successfully been able to subscribe to an http.post and get the data I need.

However now my problem is that I need to pass an auth token in the http request which I get from Storage. This is an issue because I need to wait until Storage is ready and I get my token value from it before I call the http.post request.

This is where I am trying to get my json data

getPlanograms() {

    //API URL
    let requestURL = 'https://myapiurlhere';
    let headers = new Headers({'Content-Type': 'application/json'});

    return this.storage.ready().then(() => {

        return this.storage.get('id_token').then((val) => {

            headers.append('Authorization', 'Bearer ' + this.authCredentials.token);
            let options = new RequestOptions({headers: headers});
            return this.http.post(requestURL, {}, options)
                .map(response => <Planogram[]>response.json());

        })
    });
}

Which gets called from here

 ionViewDidLoad (){
    this.merchandisingDataService.getPlanograms()
        .subscribe(Planogram => this.planograms = Planogram);
}

However, when I try to do this I get the following error

Property 'subscribe' does not exist on type 'Promise'.

What would be the best way to achieve my objective?

3 Answers

The 2020 / 2021 version of this answer is as follows, RequestOptions is deprecated, Observable.fromPromise is now simple from and flatMap is now mergeMap and you have to pipe to the mergeMap:

Dependencies / imports:

import { Observable, throwError, of, from } from 'rxjs';
import { map, catchError, mergeMap } from 'rxjs/operators';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';

Function:

listProducts(){
return from(this.storage.get('token'))
  .pipe(mergeMap(token =>{
      const headers = new HttpHeaders().append('Content-Type', 'application/json').append('Authorization', 'Bearer ' + token);
      return this.http.get(`${url}`, { headers: headers })
  }
));
}
Related