I am emitting an event in my main component:
main.component.ts
this.sharedService.cartData.emit(this.data);
Here is my sharedService.ts
import { Component, Injectable, EventEmitter } from '@angular/core';
export class SharedService {
cartData = new EventEmitter<any>();
}
In my other (Sub) Component, I want to access this value, but somehow, the subscription does not work:
dashboard.ts
private myData: any;
constructor(private sharedService: SharedService) {
this.sharedService.cartData.subscribe(
(data: any) => myData = data,
error => this.errorGettingData = <any>error,
() => this.aggregateData(this.myData));
}
Am I missing something? It works fine when I pass the data as an Injectable. Emitting the event (in the main component) happens after some REST calls.
Update
So the problem is that the Subcomponent is created after the first emit of the event. I guess in this case it is better to inject the data into the subcompnent
directly.
I have created a working plunker example using the code you provided above. https://plnkr.co/edit/LS1uqB?p=preview
View lifecycle hooks here https://angular.io/guide/lifecycle-hooks
Try this:
What that does is that it will replay the last emitted value for the "late" subscriber. If you want to have a initial value being emitted, you could use
BehaviourSubject
- it takes initial value in the constructor.Or you could pipe/chain it with
startWith
operator.