Reputation: 1386
I'm trying to update the data from one component, and receive it into another component sing Subject
and Observables
.
I am able to store data in datShareService
, but my getData
never gets called once data is updated.
I have following code structure
fileComponent.ts tries to store some data in dataShareService
{
...
//call dataShareService and update data
this.dataShareService.updateData(this.things);
...
}
dataShareService.ts would get the data and return it when asked
{
...
private outputs = new Subject<any>();
constructor() { }
getData(): Observable<any>{
console.log('getData', this.outputs.asObservable());
return this.outputs.asObservable();
}
updateData(outputs:any): void{
this.outputs.next(outputs);
console.log('datashare', this.outputs);
}
...
}
resultsComponents.ts which has subscribed to getData
method
{
...
public results : any;
private sub : Subscription;
constructor(private dataShareService: DatashareService) {
console.log(this.dataShareService);
}
ngOnInit() {
this.sub = this.dataShareService.getData().subscribe(output => {
this.results = output;
});
console.log('visual result arrived', this.results);
}
...
}
I'm almost certain that the problem is with the sequence these methods are called, yet not sure where exactly.
Upvotes: 1
Views: 75
Reputation: 2232
Use ReplaySubject instead of Subject, that way it'll emit previous values aswell
Upvotes: 0
Reputation: 877
You have put console.log('visual result arrived', this.results);
outside your subscribe method.
Put your console.log('visual result arrived', this.results);
inside subscribe method then whenever data is updated it will get printed to console.
Below is
Upvotes: 0
Reputation: 27471
if you are getting no value then you have to change your dataShareService.ts as follow
{
...
private outputs = new Subject<any>();
constructor() { }
getData(): Observable<any>{
console.log('getData', this.outputs.asObservable());
return this.outputs.asObservable();
}
updateData(outputs:any): void{
this.outputs.next({text:outputs});
console.log('datashare', this.outputs);
}
...
}
Upvotes: 1