承诺并订阅



>我有一个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!')
);
}

并且还通过调用该方法getAllCitiesObservablehttp.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);
});
});
});
}

相关内容

  • 没有找到相关文章

最新更新