>我有一个Angular2(ionic2)应用程序。我有一个请求城市的函数,但我收到一个错误,即this.cityService.getAllCities()
上不存在属性订阅。
cityPage.ts有一个这样的功能:
getCities(){
this.cityService.getAllCities()
.subscribe(cityData => { this.cityList = cityData; },
err => console.log(err),
() => console.log('Complete!')
);
}
我的 cityService.getAllCities() 函数如下所示:
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);
});
});
});
}
编辑
根据评论,我像这样更改了我的函数:
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);
});
});
});
}
在我的console.log(result)
中,我接收数据,但数据永远不会返回到我的getCities()
函数。此外,不调用console.log('Complete!')
。
它引发错误的原因,因为无论何时发出数据.subscribe
该方法都可以在Observable
上侦听。在这里,从getAllCities
方法返回一个promise
您可以对其应用.then
函数以获取从该Promise
返回的数据
getCities() {
this.cityService.getAllCities()
.then(
cityData => { this.cityList = cityData; },
err => console.log(err),
() => console.log('Complete!')
);
}
并且还通过调用该方法getAllCities
Observablehttp.get()
从方法返回.toPromise()
承诺。
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);
});
});
});
}