Angular 2 Component听取服务中的变化

Han*_*Che 24 angular2-services angular2-changedetection angular

我有一个关于变化检测的简单问题.

我有一个组件和一个(全局)服务,里面有一个布尔值.如果该布尔值发生变化,如何让组件监听该布尔值并执行函数?

谢谢!

Sam*_*rie 33

根据布尔值的更改方式,您可以将其作为Observable<boolean>服务公开,然后在组件中订阅该流.您的服务看起来像:

@Injectable()
export class MyBooleanService {
    myBool$: Observable<boolean>;

    private boolSubject: Subject<boolean>;

    constructor() {
        this.boolSubject = new Subject<boolean>();
        this.myBool$ = this.boolSubject.asObservable();
    }

    ...some code that emits new values using this.boolSubject...
}
Run Code Online (Sandbox Code Playgroud)

然后在你的组件中你会有这样的东西:

@Component({...})
export class MyComponent {
    currentBool: boolean;

    constructor(service: MyBooleanService) {
        service.myBool$.subscribe((newBool: boolean) => { this.currentBool = newBool; });
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,根据你需要对bool值做什么,你可能需要做一些其他事情来让你的组件更新,但这是使用observable的要点.

另一种选择是在模板中使用异步管道,而不是在构造函数中显式订阅流.但是,这取决于你需要对bool值做什么.

  • 你可以从rxjs获得Subject (3认同)
  • @SamStorie嘿,通过声明主题,可以用1行来完成:`private boolSubject = new Subject <boolean>();`.好伙伴!;) (2认同)

Thi*_*ier 13

Sam的回答是完全正确的.我只想补充一点,您还可以利用TypeScript setter自动触发事件以进行更改:

@Injectable()
export class MyBooleanService {
    myBool$: Observable<boolean>;

    private boolSubject: Subject<boolean>;

    constructor() {
        this.boolSubject = new Subject<boolean>();
        this.myBool$ = this.boolSubject.asObservable();
    }

    set myBool(newValue) {
      this._myBool = newValue;
      this.boolSubject.next(newValue);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 嗨,`this._myBool`来自哪里?无法弄清楚对不起 (5认同)
  • 它应该是服务上的私有布尔值,他只是忘了将它包含在他的示例代码中. (3认同)