Promise and subscribe
I have an Angular2 (ionic2) app. I have a function that asks for cities, but I get an error that the resource subscription does not exist for this.cityService.getAllCities()
.
cityPage.ts has a function like this:
getCities(){
this.cityService.getAllCities()
.subscribe(cityData => { this.cityList = cityData; },
err => console.log(err),
() => console.log('Complete!')
);
}
my cityService.getAllCities () function looks like this:
getAllCities(){
return new Promise (resolve => {
this.storage.ready().then(() => {
this.storage.get('authData').then(authData => {
let hdr = new Headers({'Content-Type': 'application/json', 'Authorization': 'Bearer ' +
authData.access_token });
let opt = new RequestOptions({ headers: hdr });
return this.http.get(AppSettings.API_GET_CITIES).map(res => <CityModel[]> res.json(), opt);
}).catch(() => {
//resolve(false);
});
});
});
}
Edit
Based on the comment, I changed my function as follows:
getAllCities(){
return Observable.create(resolve => {
this.storage.ready().then(() => {
this.storage.get('authData').then(authData => {
let hdr = new Headers({'Content-Type': 'application/json', 'Authorization': 'Bearer ' +
authData.access_token });
console.log('access_token ' + authData.access_token);
let opt = new RequestOptions({ headers: hdr });
return this.http.get(AppSettings.API_GET_CITIES,opt).map(res => <CityModel[]> res.json()).subscribe((result) => {
console.log(result);
resolve = result;
});
}).catch(() => {
//resolve(false);
});
});
});
}
In mine, console.log(result)
I am getting data, but the data is never returned to my function getCities()
. Also console.log('Complete!')
not called.
source to share
The reason it throws an error is because the method .subscribe
is Observable
listenable whenever it emits data. Here, from the method getAllCities
you return promise
, you can apply a function to it .then
to get the data returned from thispromise
getCities() {
this.cityService.getAllCities()
.then(
cityData => { this.cityList = cityData; },
err => console.log(err),
() => console.log('Complete!')
);
}
And also return the promise from the method getAllCities
by calling the method .toPromise()
on the http.get()
Observable.
getAllCities(){
return new Promise (resolve => {
this.storage.ready().then(() => {
this.storage.get('authData').then(authData => {
let hdr = new Headers({'Content-Type': 'application/json', 'Authorization': 'Bearer ' +
authData.access_token });
let opt = new RequestOptions({ headers: hdr });
//returned promise from here.
return this.http.get(AppSettings.API_GET_CITIES)
.map(res => <CityModel[]> res.json(), opt)
.toPromise();
}).catch(() => {
//resolve(false);
});
});
});
}
source to share