Home > OS >  service using behaviourSubject returns [object][object]
service using behaviourSubject returns [object][object]

Time:11-09

I have a service which looks like below:

      private sharedData = new BehaviorSubject<any>(null);

      constructor() { }

       getData(){
        return this.sharedData;
          }

         setData(data:any){
         this.sharedData.next(data);
         }

     }

I have my app.component.ts which uses this service :

        this.http.post("url",quote).subscribe(s=>{

        this.dataService.setData(s);

        });

here is the component i consume it(receiver):

  constructor(private dataService:DataService) { }

   ngOnInit(): void {
   const data = this.dataService.getData();
   alert(data) }

the data contains string,in my app.component.ts i can log and see it,but seems there is race between alert and service,when the alert fires the fist and shows [object][object] any idea?

CodePudding user response:

In this case, getSharedData() returns the behavior subject itself, so the sensible thing to do in this case is to subscribe to it in order to receive the data that you are emitting when calling setData.

In the receiver component:

ngOnInit(): void {
  this.dataService.getData().pipe(
    filter(data => !!data)
  ).subscribe(data => {
    alert(data)
  });
}

CodePudding user response:

When you do this, you are not getting the latest value, you are returning the BehaviourSubject object

getData(){
  return this.sharedData;
}

What you need is to subscribe to your sharedData BehaviourSubject

sharedData.subscribe(console.log) ;

That should show you your data as received from the post method.

Basically you react to when the data has arrived, you dont call a method when you think the data is ready.

For more details checkout this examples: https://www.learnrxjs.io/learn-rxjs/subjects/behaviorsubject

  • Related