繁体   English   中英

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

[英]Cannot read property 'subscribe' of undefined TypeError

我正在开发一个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,以便第一种方法可以解决这个问题。 谢谢你的帮助。

您的问题是,当this.countriesObservable undefined ,您正在调用this.storage.get(...).then(...) 在tha的回调内,您可以设置this.countriesObservable

问题是,当你到达return this.countriesObservable ,回调then没有执行,所以你还是回来undefined

您必须分配this.countriesObservable到一个新的Observable之前调用this.storage.get (也许一个Subject ),然后,里面then ,你只听你要回报可观的,其调用内部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;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM