簡體   English   中英

無法通過 BehaviorSubject 訪問數據的屬性。 BehaviorSubject 上不存在屬性

[英]Unable to access property of data through BehaviorSubject. Property does not exist on BehaviorSubject

使用 BehaviourSubject 在我的應用程序中設置共享數據時,我無法訪問數據的屬性。 獲取錯誤:-

**

'BehaviourSubject' 類型不存在屬性

**

共享服務.ts

setCommonData(data): void {
  this.commonData.next(data);
}
getCommonData(): Observable<BehaviorSubject<any>> {
  return this.commonData;
}

app.component.ts

// result = {id: number, name: string, info: {}}
getData(): void {
    this.dataService.getApi(url, {}, true).subscribe((result) => {
        this.sharedService.setCommonData(result);
    }
}

子組件.ts

displayData(): void {
    this.sharedService.getCommonData().subscribe((data) => {
         this.displatData = data // works
         this.info = data.info // property info does not exist on type 'BehaviourSubject<any>'
    });
}

您正在返回BehaviorSubject的可觀察對象。 相反,您需要將BehaviorSubject作為可觀察對象返回。

嘗試以下

setCommonData(data): void {
  this.commonData.next(data);
}

getCommonData(): Observable<any> {         // <-- return `Observable` here
  return this.commonData.asObservable();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM