【发布时间】:2017-09-21 15:11:51
【问题描述】:
我有一个 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!')。
【问题讨论】:
-
Promise.Then... 订阅观察者
标签: angular ionic2 angular2-services