简体   繁体   中英

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

While using BehaviourSubject to set shared data across my application, I am unable to access the properties of the data. Getting error :-

**

property does not exist on type 'BehaviourSubject'

**

SharedService.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);
    }
}

child.component.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>'
    });
}

You're returning an observable of the BehaviorSubject . Instead you need to return the BehaviorSubject as an observable.

Try the following

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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