Reputation: 908
according to this guide: Parent and children communicate via a service
I am tring to use a shared service as an alternative to EventEmitter, since EventEmitter only communicates between parent and child component. This is not the case in my situation, but both components are sharing the same Service (MasterdataService).
It seems that my subscription cannot intercept the announcement. There are no errors in the browser console neither, except the log information that the announcemend has been triggered. I would really like to know what am I missing here.
MasterdataService
import {Injectable} from 'angular2/core';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class MasterdataService {
private _updateAnnouncedSource = new Subject<string>();
updateAnnounced$ = this._updateAnnouncedSource.asObservable();
announceUpdate(value: string) {
console.log('announcement to update list has been triggered');
this._updateAnnouncedSource.next(value);
}
}
MasterdataComponent (announcing the update)
@Component({
providers: [MasterdataService]
})
export class MasterdataComponent {
constructor(private masterdataService: MasterdataService) {}
newMerchant(merchantIdInput: HTMLInputElement, merchantNameInput: HTMLInputElement) {
this.masterdataService.announceUpdate('newMerchant');
}
}
MasterdataListComponent (subscribed to the Subject)
@Component({
providers: [MasterdataService]
})
export class MasterdataListComponent {
subscription:Subscription;
constructor(private masterdataService:MasterdataService) {
this.subscription = this.masterdataService.updateAnnounced$.subscribe(
value => {
console.log('update announcement received... updating list with value ', value);
this.merchants = this.masterdataService.getAllMerchants();
})
}
}
Upvotes: 1
Views: 1144
Reputation: 908
My Problem was not the code, rather how I use/declare the Service in my components. By defining that Service in both components in the decorator
@Component({
providers: [MasterdataService]
})
angular instantiates for each component a seperate service. This way, no communication between the two components can be executed.
Since I have a root component (AppComponent) I can declare the service in that decorator and angular takes care of the rest (DI a.k.a Dependency Injection) by having the service as an argument in the constructor of both component classes.
Upvotes: 1