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

后端 未结 6 856
佛祖请我去吃肉
佛祖请我去吃肉 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:08

    ChangeDetectorRef is not option to use here. It is looking for changes in a given component and its children.

    In your case It would be better to use ApplicationRef:

    import {Injectable, ApplicationRef } from '@angular/core';
    
    @Injectable()
    export class MyService {
      private count: number = 0;
      constructor(private ref: ApplicationRef) {}
    
      increment() {
        this.count++;
        this.ref.tick();
      }
    }
    

    I checked this solution with Observables and it works without any problems:

    import { ApplicationRef, Injectable } from '@angular/core';
    import { Observable, ReplaySubject } from "rxjs/Rx";
    import * as childProcess from 'child_process';
    
    @Injectable()
    export class Reader {
    
        private output: ReplaySubject = new ReplaySubject(0);
    
        constructor(private ref: ApplicationRef) {
            var readerProcess = childProcess.spawn('some-process');
            readerProcess.stdout.on('data', (data) => {
                this.output.next(data.toString());
                this.ref.tick();
            });
        }
    
        public getOutput():Observable {
            return this.output;
        }
    }
    

    and here is a component which uses it:

    import {Component} from '@angular/core';
    import { ReplaySubject, Observable } from "rxjs/Rx";
    
    import { Reader } from './reader/reader.service';
    
    @Component({
        selector: 'app',
        template: `
        output:
        
    {{output}}
    ` }) export class App { public output: string; constructor(private reader: Reader) {} ngOnInit () { this.reader.getOutput().subscribe((val : string) => { this.output = val; }); } }

提交回复
热议问题