Angular2 - 使用服务的组件之间的交互 [英] Angular2 - Interaction between components using a service

查看:21
本文介绍了Angular2 - 使用服务的组件之间的交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个组件 A 和 B,其中组件 A 包含一个按钮.我希望当用户点击这个按钮时,在组件 B 上触发一个函数

I have two component A and B, where component A contains a button. I wish when user click on this button, fire a function on component B

<A></A>
<router-outlet></router-outlet>

组件 B 是使用路由呈现的.我正在考虑使用带有可观察布尔值的服务,指示是否单击了 A 中的按钮.这是实现它的正确方法吗?

And the component B is rendered using routing.I am considering using a service with an observable boolean that indicate if the button in A is clicked. Is this the right way to achieve it ?

推荐答案

共享服务是非相关组件之间常见的通信方式.您的组件需要使用服务的单个实例,因此请确保它在根级别提供.

Shared service is a common way of communication between non-related components. Your components need to use a single instance of the service, so make sure it's provided at the root level.

使用 BehaviorSubject 作为数据委托的示例:

共享服务:

@Injectable()
export class SharedService {

    isVisibleSource: BehaviorSubject<boolean> = new BehaviorSubject(false);

    constructor() { }
}

组件 1:

export class Component1 {

    isVisible = false;

    constructor(private sharedService: SharedService) { }

    onClick(): void {
        this.isVisible = !this.isVisible;
        this.sharedService.isVisibleSource.next(this.isVisible);
    }
}

组件 2:

export class Component2 {

    constructor(private sharedService: SharedService) { }

    ngOnInit(): void {
        this.sharedService.isVisibleSource.subscribe((isVisible) => {
            console.log('isVisible: ', isVisible); // => true/false
        });
    }
}

值得一提的是,BehaviorSubject 在订阅时返回它持有的最后一个值,因此上面示例中的组件将在实例化后立即更新为最新值.

It is worth mentioning that BehaviorSubject upon a subscription returns the last value it holds, therefore the component from the example above will be updated with the most recent value immediately after the instantiation.

BehaviorSubject 还允许在不订阅的情况下获取其最新值:

BehaviorSubject also allows to get its most recent value without even subscribing to it:

this.sharedService.isVisibleSource.getValue(); // => true/false

这篇关于Angular2 - 使用服务的组件之间的交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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