从另一个组件调用一个组件中的函数 [英] call a function in a component from another component

查看:32
本文介绍了从另一个组件调用一个组件中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Angular2 中,假设我有 component1(将其用作左侧面板导航器)和 component2 .这两个组件彼此不相关(兄弟姐妹、父母和孩子,...).如何从component2调用component1中的函数?我不能在这里使用事件绑定.

In Angular2 , assume I have component1(use it as left panel navigator) and component2 .these two components are not related to each other (sibling, parent and child, ...). how can I call a function in component1 from component2? I cant use event binding here.

推荐答案

您可以使用 Angular BehaviorSubject 与非相关组件进行通信.

You can use angular BehaviorSubject for communicating with non related component.

服务文件

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';


@Injectable()
export class commonService {
    private data = new BehaviorSubject('');
    currentData = this.data.asObservable()

    constructor() { }

    updateMessage(item: any) {
        this.data.next(item);
    }

}

第一个组件

constructor(private _data: commonService) { }
shareData() {
      this._data.updateMessage('pass this data');
 }

第二部分

constructor(private _data: commonService) { }
ngOnInit() {
     this._data.currentData.subscribe(currentData => this.invokeMyMethode())
}

使用上述方法,您可以轻松调用方法/与不相关的组件共享数据.

Using above approach you can invoke a method/share data easily with non related components.

更多信息在这里

这篇关于从另一个组件调用一个组件中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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