我正在开发一个 Ionic 应用程序,并且我有以下调用 observable 的方法:
getCountryById(id: number): Promise<Country> {
return new Promise((resolve, reject) => {
this.getCountries().subscribe(countries => {
for (let country of countries) {
if (country.Id == id) {
resolve(country);
}
}
resolve(undefined);
}, err => reject(err));
})
}
另一种方法:
getCountries(): Observable<Country[]> {
if (this.countries) {
return Observable.of(this.countries);
} else if (this.countriesObservable) {
return this.countriesObservable;
} else {
this.storage.get(AppSettings.STORAGE_KEYS.LANGUAGE_APP).then(
language=>{
this.countriesObservable = this.http.get(AppSettings.API_URL + 'api/Countries?locale=' + language).map(json => {
delete this.countriesObservable; // when the cached countries is available we don't need the `countriesObservable` reference anymore
this.countries = json as Country[];
this.countries = this.countries.sort(function (a, b) { return (a.Name > b.Name) ? 1 : ((b.Name > a.Name) ? -1 : 0); });
return this.countries;
}).share();
}
).catch(err=>{
});
return this.countriesObservable;
}
}
我很确定我返回了错误的数据。我应该如何重构第二个方法以返回有效的 Observable,以便第一个方法可以解决这个问题。我仍在尝试围绕 Promise 和 Observable 进行思考。感谢您的帮助。
最佳答案
您的问题是,当 this.countriesObservable
为 undefined
时,您正在调用 this.storage.get(...).then(.. .)
。在对 tha Promise 的回调中,您正在设置 this.countriesObservable
。
问题是,当您到达 return this.countriesObservable
时,对 then
的回调尚未执行,因此您仍然返回 未定义
。
在调用 this.storage.get
之前,您必须将 this.countriesObservable
分配给新的 Observable
(可能是一个 Subject
) code>),然后,在 then
中,您只需监听要返回的 Observable,并在其对 subscribe
的调用中,提供 this.countriesObservable
包含您想要的数据:
const _subject = new Subject<Country[]>();
this.countriesObservable = _subject;
this.storage.get(AppSettings.STORAGE_KEYS.LANGUAGE_APP).then(
language=>{
this.http.get(AppSettings.API_URL + 'api/Countries?locale=' + language).map(json => {
delete this.countriesObservable; // when the cached countries is available we don't need the `countriesObservable` reference anymore
this.countries = json as Country[];
this.countries = this.countries.sort(function (a, b) { return (a.Name > b.Name) ? 1 : ((b.Name > a.Name) ? -1 : 0); });
return this.countries;
}).subscribe(countries => _subject.next(countries));
}
).catch(err=>{});
return this.countriesObservable;
您可能需要进行一些调整,但这就是想法。希望对您有帮助。
关于javascript - 无法读取未定义 TypeError 的属性 'subscribe',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50008809/