是否可以将 `ChangeDetectorRef` 添加到 Angular 4 服务的构造函数中?

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

我有一个服务文件提醒 Subjects 的系统,当设置值时,它也会使用 setTimeout() 方法将自己设置为在 3 秒后重置为空。但是在将 changeDetection: ChangeDetectionStrategy.OnPush 添加到 app.component.ts 之后,它似乎搞砸了所有 SetTimeout() 方法。有没有办法在服务中使用 ChangeDetectorRef

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);
}

没有 ChangeDetectionStrategy

我怀疑问题是 setTimeout() 不再工作了。

问题是组件不会 运行 更改检测,即使 ApplicationRef.tick() 也是如此,因为 OnPush 未标记为检查的组件将被跳过。

我建议您在服务中使用 Observable 并在组件中订阅它,然后使用 observable 发出一个事件,并在组件调用 ChangeDetectorRef.markForCheck()ChangeDetectorRef.detectChanges()