无法读取未定义的TypeError属性'subscribe'

时间:2018-04-24 18:44:39

标签: 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 (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。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

问题在于,当this.countriesObservableundefined时,您正在呼叫this.storage.get(...).then(...)。在回调中承诺你正在设置this.countriesObservable

问题在于,当您到达return this.countriesObservable时,then的回调尚未执行,因此您仍然会返回undefined

在致电this.countriesObservable(可能是Observable)之前,您必须将this.storage.get分配给新的Subject,然后在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;

您可能需要进行一些调整,但这是个主意。希望它能为你服务。