gpt4 book ai didi

angular - promise 并订阅

转载 作者:太空狗 更新时间:2023-10-29 17:19:10 26 4
gpt4 key购买 nike

我有一个 Angular2 (ionic2) 应用程序。我有一个请求城市的函数,但我收到一个错误,指出 Property subscribe does not exists on 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!')
);
}

并且还通过在 http.get() Observable 上调用 .toPromise() 方法从 getAllCities 方法返回 promise 。

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);
});
});
});
}

关于angular - promise 并订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43596530/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com