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

查看:85
本文介绍了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: boolean = 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() {
        this.sharedService.isVisibleSource.subscribe((isVisible: boolean) => {
            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天全站免登陆