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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With