Answer the question
In order to leave comments, you need to log in
Tracking changes in an Angular 2+ service?
Good afternoon everyone! I have a certain situation. There are 2 components that have 1 common parent, there is also a service for these components. So in one of the components I have a checkbox, when I change it, I overwrite a certain field in the service. I need to make sure that when this field of the service changes, the same field is passed to the second component, where it is already displayed
Answer the question
In order to leave comments, you need to log in
Service MyService
private ck = new BehaviorSubject(false);
public setCk(val: boolean): void {
this.ck.nex(val);
}
public getCk(): Observable<boolean> {
return this.ck.asObservable();
}
// можно оформить как аксессоры, но так наглядней
private subs = new Subscription();
public ck: boolean;
constructor(private service: MyService) {}
ngOnInit() {
const s0 = this.service.getCk().subscribe(ck => this.ck = ck); // тут можно добавить какие-то действия при изменении данных
this.subs.add(s0);
}
ngOnDestroy() {
this.subs.unsubscribe();
}
If in general, then look at Observable/Observer. There is a Subject (or ReplaySubject) class that combines the functionality of Observable and Observer. Those. in the service you create methods 1 - which returns this Subject, 2 - which changes its values. In components, subscribe to changes, and when rewriting a field in a service, do .next() to this Subject.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question