Trigger update of component view from service - No Provider for ChangeDetectorRef

后端 未结 6 854
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-09 01:22

I would like to udpate my application view, triggered by events from service.

One of my services injects the ChangeDetectorRef. Compilation works, but I am getting a

6条回答
  •  眼角桃花
    2020-12-09 02:04

    To use ApplicationRef is a good solution. I have a few more solutions:

    1. Using setTimeout

      @Injectable()
      export class MyService {
        private count: number = 0;
        constructor(){}
      
        increment() {
          setTimeout(() => this.count++, 0);
        }
      }
      
    2. Using Promise

      @Injectable()
      export class MyService {
        private count: number = 0;
        constructor(){}
      
        increment() {
          Promise.resolve().then(() => this.count++);
        }
      }
      

    Both solutions force Angular to trigger change detection, if you are using Zone.js for change detection - this is the default way and 99% of the apps use it.

提交回复
热议问题