Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 452
dr_ermio Avatar asked May 14 '17 17:05

dr_ermio


1 Answers

You could consume with .then() by changing:

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

Or, you could make getPlanograms return an Observable.

getPlanograms() {   

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

    // this converts from promise to observable
    return Observable.fromPromise(this.storage.ready()
        .then(() => 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 converts from observable to promise
                // (returned by response.json())
                .map(response => <Planogram[]>response.json());
        });
    }));
}

Now you can consume with .subscribe() as you did in the question.

like image 121
0xcaff Avatar answered Sep 16 '22 11:09

0xcaff