Reputation: 212
I am trying to pass a Javascript Object as an Observable to a sibling component.
To do so, I created a service pass.service.ts
that contains a variable declaration as follows:
public passedData:any
this.fb.user$.subscribe(data => {
this.passservice.passedData = of(data);
})
By doing so, I can subscribe to the observable in my other component. I am retrieving the data in the other component using:
this.passservice.passedData.subscribe(data => {
this.data = data
})
I am not getting any new updates, once data
changes though.
The behaviour is the same as if I'd subscribe by using Observable.first()
What am I missing?
Upvotes: 0
Views: 1138
Reputation: 14089
You need to use a Subject (Subjects are also Observables). import { Subject } from 'rxjs';
Service
Create a Subject in your service. This Subject will be used by your components to share data.
public passedData = new Subject<any>();
Component 1
Pass new data into the Subject by calling next
.
this.passService.passedData.next(data);
To pass all events including error
and complete
events from one Observable to a Subject you could do: this.fb.user$.subscribe(this.passService.passedData);
But this will mean this.passService.passedData
just mirrors this.fb.user$
and you could just aswell use this.fb.user$
directly instead.
Component 2
Get notified about new data from the Subject by subscribing.
this.passService.passedData.subscribe(data => this.data = data);
Upvotes: 1
Reputation: 60518
You could just define the property in your service as this:
user$ = this.fb.user$;
Then you could subscribe to it in any component that needs it.
But it actually looks like you already have another service (fb?) that has a user$ property? If so, you could subscribe to that user$ property in each component that needs it.
You could also pipe it through a shareReplay(1)
to share the result with all subscribers:
user$ = this.fb.user$.pipe(shareReplay(1));
I put together an example of passing a stream to a child component here:
https://stackblitz.com/edit/angular-todos-deborahk-child
Upvotes: 1
Reputation: 11345
Use subject makes more sense, or perhaps inject this.fb to your service if you are using dependency injection
this.passservice.passedData=new Subject()
this.fb.user$.subscribe(this.passservice.passedData)
Upvotes: 1