R
R
Roman Chasovitin2018-06-15 09:56:09
JavaScript
Roman Chasovitin, 2018-06-15 09:56:09

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

2 answer(s)
A
Anton Shvets, 2018-06-15
@Xuxicheta

Service MyService

private ck = new BehaviorSubject(false);
public setCk(val: boolean): void {
  this.ck.nex(val);
}
public getCk(): Observable<boolean> {
  return this.ck.asObservable();
}
// можно оформить как аксессоры, но так наглядней

In components
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();
}

Well, when changing the field, you do this.service.setCk(...)
Also, when receiving data in a reactive form from the service, sometimes you need to manually pull detectChanges
ngRx.store, you can also see the async pipe

A
Anton, 2018-06-15
@sHinE

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 question

Ask a Question

731 491 924 answers to any question