Prav
Prav

Reputation: 2894

Is it possible to add `ChangeDetectorRef` to the constructor of Angular 4 service?

I have a service file that alert system of Subjects that when setting the value it also set itself to reset to null after 3 seconds using setTimeout() method. But after adding changeDetection: ChangeDetectionStrategy.OnPush to the app.component.ts it seem to screw up all the SetTimeout() method. Is there a way to use ChangeDetectorRef in a service?

storage.service.ts

private errorMsg: Subject < string > = new Subject();
private successMsg: Subject < string > = new Subject();

constructor() {}

setSuccessAlert(msg: string) {
  this.successMsg.next(msg);
  setTimeout(() => {
    this.successMsg.next(null);
  }, 3000);
}

Without ChangeDetectionStrategy enter image description here

Upvotes: 1

Views: 3172

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657771

I doubt the issue is that setTimeout() isn't working anymore.

The problem is that the components don't run change detection, even with ApplicationRef.tick() because OnPush components that are not marked for check, are skipped.

I'd suggest you use an Observable in the service and subscribe to it in the components, and then emit an event using the observable and in the subscriptions in components call ChangeDetectorRef.markForCheck() or ChangeDetectorRef.detectChanges()

Upvotes: 4

Related Questions