Angular 2 组件监听服务变化 [英] Angular 2 Component listen to change in service

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

问题描述

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

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,然后订阅该流在您的组件中.您的服务将类似于:

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 值做什么,您可能需要做一些其他事情来更新您的组件,但这是使用 observable 的要点.请注意,您需要在某个时候取消订阅 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 组件监听服务变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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