Angular 2 Component侦听服务变更 [英] Angular 2 Component listen to change in service

查看:49
本文介绍了Angular 2 Component侦听服务变更的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 and execute a function if that boolean changes?

谢谢!

推荐答案

根据布尔更改的方式,您可以将其公开为服务上的Observable<boolean>,然后在组件中订阅该流.您的服务如下所示:

Depending on how that boolean changes you could expose it as an Observable<boolean> on your service, and then subscribe to that stream in your component. Your service would look something like:

@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...
}

然后在您的组件中,您将得到以下内容:

Then in your component you would have something like this:

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

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

现在,根据您需要对该bool值执行什么操作,您可能需要做一些其他事情来使组件进行更新,但这是使用可观察对象的要旨.请注意,您可能希望在某个时候退订myBool $流,以防止内存泄漏和意外的副作用.

Now depending on what you need to do with that bool value you may need to do some other things to get your component to update, but this is the gist of using an observable. Note, you will want to unsubscribe from the myBool$ stream at some point to prevent memory leaks and unexpected side effects.

另一个选择是您在模板中使用异步管道,而不是在构造函数中明确订阅流.这也将确保订阅自动处理.同样,这取决于您到底需要对bool值进行什么操作.

Another option is you use the async pipe within your template instead of explicitly subscribing to the stream in the constructor. That will also ensure the subscription is disposed of automatically. Again though, that depends on what exactly you need to do with the bool values.

这篇关于Angular 2 Component侦听服务变更的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆