Angular 4 emitting and subscribing to an event on a shared service
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 for some reason the subscription doesn't 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 data as Injectable. The highlighting of the event (in the main component) happens after some REST calls.
************** Update ***************** So the problem is that the Subcomponent is created after the first event is emitted. I think in this case it is better to inject data directly into the subcomponent.
+3
source to share
1 answer
I created an example of a working plunger using the above code. https://plnkr.co/edit/LS1uqB?p=preview
import { Component, NgModule, Injectable, EventEmitter, AfterViewInit } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@Injectable()
export class SharedService {
cartData = new EventEmitter<any>();
}
@Component({
selector: 'app-app',
template: `
<h1>
Main Component <button (click)="onEvent()">onEvent</button>
</h1>
<p>
<app-dashboard></app-dashboard>
</p>
`,
})
export class App implements AfterViewInit {
data: any = "Shared Data";
constructor(private sharedService: SharedService) {
}
ngAfterViewInit() {
this.sharedService.cartData.emit("ngAfterViewInit: " + this.data);
}
onEvent() {
this.sharedService.cartData.emit("onEvent: " + this.data);
}
}
@Component({
selector: 'app-dashboard',
template: `
<h2>
Dashboard component
</h2>
<p>
{{myData}}
</p>
`,
})
export class AppDashboard implements AfterViewInit {
myData: any;
constructor(private sharedService: SharedService) {
this.sharedService.cartData.subscribe(
(data: any) => {
console.log(data);
this.myData = data;
});
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, AppDashboard ],
providers: [ SharedService ],
bootstrap: [ App ]
})
export class AppModule {}
View lifecycle bindings here https://angular.io/guide/lifecycle-hooks
+4
source to share