无法读取未定义类型错误的属性“订阅”

Posted

技术标签:

【中文标题】无法读取未定义类型错误的属性“订阅”【英文标题】:Cannot read property 'subscribe' of undefined TypeError 【发布时间】:2018-10-05 03:15:34 【问题描述】:

我正在开发一个 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】:

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

问题是,当您到达return this.countriesObservable 时,尚未执行对then 的回调,所以您仍然返回undefined

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

您可能需要进行一些调整,但这就是我们的想法。希望对您有所帮助。

【讨论】:

以上是关于无法读取未定义类型错误的属性“订阅”的主要内容,如果未能解决你的问题,请参考以下文章

无法读取未定义类型错误的属性“推送”:无法读取未定义错误的属性“推送”

未捕获的类型错误:无法读取未定义的属性“区域”?

错误:`未捕获(承诺中)类型错误:无法读取未定义的属性'doc'`

未捕获的类型错误:无法读取未定义的属性 toLowerCase

JQuery:未捕获的类型错误:无法读取未定义的属性“调用”

NextJS:未捕获的类型错误:无法读取未定义的属性(读取“属性”)