【问题标题】:call a function in a component from another component从另一个组件调用一个组件中的函数
【发布时间】:2017-07-13 07:15:02
【问题描述】:

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

【问题讨论】:

  • 您可能会使用service 来管理该连接。
  • 使用通量模式——服务是事件的分发者,组件是订阅者。组件并不真正了解彼此。这可能有用:stackoverflow.com/questions/42219858/…
  • @ryannjohnson 在 component1 中,我有插值 {{total}} 需要更新并立即显示在左侧面板中。如果我只是调用 service ,我该如何更新这个变量?
  • @pixelbits 我去看看能不能用?
  • @SarahN Checkout @seidme 的回答如下。将服务注入组件后,您可以直接在模板中引用其属性,即{{ myservice.total }}

标签: angular events event-handling components listener


【解决方案1】:

共享服务是非相关组件之间的常用通信方式。 您的组件需要use a single instance of the service,因此请确保它在根级别提供。

共享服务:

@Injectable()
export class SharedService {

    componentOneFn: Function;

    constructor() { }
}

组件一:

export class ComponentOne {

    name: string = 'Component one';

    constructor(private sharedService: SharedService) {
        this.sharedService.componentOneFn = this.sayHello;
    }

    sayHello(callerName: string): void {
        console.log(`Hello from ${this.name}. ${callerName} just called me!`);
    }
}

组件二:

export class ComponentTwo {

    name: string = 'Component two';

    constructor(private sharedService: SharedService) {
        if(this.sharedService.componentOneFn) {
            this.sharedService.componentOneFn(this.name); 
            // => Hello from Component one. Component two just called me!
        }
    }
}

这篇文章也可能有帮助:Angular 2 Interaction between components using a service

【讨论】:

  • 这在 2017 年 10 月 24 日仍然有效吗?完全按照指定进行了尝试,但是从 comp2 调用时 comp1 的名称似乎未定义。
【解决方案2】:

您可以使用 Angular BehaviorSubject 与不相关的组件进行通信。

服务文件

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())
}

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

More info here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-06
    • 2017-01-09
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多