Javascript 无法读取未定义类型错误的属性“subscribe”
我正在开发一个Ionic应用程序,我有以下方法调用一个observable:Javascript 无法读取未定义类型错误的属性“subscribe”,javascript,angular,typescript,ionic2,promise,Javascript,Angular,Typescript,Ionic2,Promise,我正在开发一个Ionic应用程序,我有以下方法调用一个observable: getCountryById(id: number): Promise<Country> { return new Promise((resolve, reject) => { this.getCountries().subscribe(countries => { for (let country of countries) { if
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未定义时,您调用的是this.storage.get…,然后。。。。在回调中,承诺您正在设置this.countriesObservable 问题是,当返回this.countriesObservable时,对then的回调尚未执行,因此仍然返回undefined 在调用this.storage.get可能是一个主题之前,您必须将this.countriesObservable分配给一个新的Observable,然后,在then中,您只需收听要返回的Observable,并在其订阅调用中,向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;
你可能需要做一些调整,但这就是你的想法。希望对你有用