Search code examples
angularobservablebehaviorsubjectsubject

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

Solution

  • 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();
    }