I am working on a project where parents and children need to communicate via service. Following this article in the official documentation I am not able to make it work.
This is the service I created:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable()
export class CommonService {
private _propertyChangeAnnouncedSource = new Subject<string>();
propertyChangeAnnounced$ = this._propertyChangeAnnouncedSource.asObservable();
public announcePropertyChange(data: string) {
this._propertyChangeAnnouncedSource.next(data);
}
}
In the parent component, I import all I need:
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss'],
providers: [CommonService]
})
export class ParentComponent implements OnInit {
constructor(private _commonService: CommonService) {
}
tellChild(data): void {
this._commonService.announcePropertyChange(data);
}
}
This is the child's code:
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit, OnDestroy {
private subscription: Subscription;
constructor(private _commonService: CommonService) {
this.subscription = this._commonService.propertyChangeAnnounced$.subscribe(
data => {
console.log(data);
});
}
}
When I call the announcePropertyChange the child is not responding. Any suggestion?
Thanks!