Angular 2 Component听取服务中的变化

时间:2016-03-28 11:57:17

标签: angular angular2-services angular2-changedetection

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

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

谢谢!

2 个答案:

答案 0 :(得分:32)

根据布尔值的更改方式,您可以在服务上将其公开为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...
}

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

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

    constructor(service: MyBooleanService) {
        service.myBool$.subscribe((newBool: boolean) => { this.currentBool = newBool; });
    }
}

现在,根据你需要对bool值做什么,你可能需要做一些其他事情来让你的组件更新,但这是使用observable的要点。注意,您需要在某些时候取消订阅myBool $流,以防止内存泄漏和意外的副作用。

另一种选择是在模板中使用异步管道,而不是在构造函数中显式订阅流。这也将确保订阅自动处理。但同样,这取决于您对bool值的具体要求。

答案 1 :(得分:12)

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

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