Angular 2 Component listen to change in service

前端 未结 2 1238
暗喜
暗喜 2020-12-14 16:12

I\'ve a simple question about change detection.

I have a component and a (global) service with a boolean inside. How can I make the component listen to that boolean

2条回答
  •  天涯浪人
    2020-12-14 16:51

    The Sam's answer is completely right. I would just want to add that you could also leverage a TypeScript setter to automatically trigger the event for changes:

    @Injectable()
    export class MyBooleanService {
        myBool$: Observable;
    
        private boolSubject: Subject;
    
        constructor() {
            this.boolSubject = new Subject();
            this.myBool$ = this.boolSubject.asObservable();
        }
    
        set myBool(newValue) {
          this._myBool = newValue;
          this.boolSubject.next(newValue);
        }
    }
    

提交回复
热议问题