如何在angular2中将功能从一个组件触发到另一个组件? [英] How to trigger function from one component to another in angular2?

查看:322
本文介绍了如何在angular2中将功能从一个组件触发到另一个组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个组件componentA和componentB.他们都是同胞,都是componentMother的子代.

I have two components componentA and componentB. Both of them are sibblings, and are children of componentMother.

我要使它这样,当我单击componentA上的按钮时,它会触发componentB上的函数调用.

I want to make it such that when I click on a button on componentA, it triggers a function call on componentB.

使用具有可观察性的服务并让componentA发出componentB订阅的事件的方法是这样做还是有更好/最佳的实践方法?

Is the way to do this using a service with an observable and having componentA emit events that componentB subscribes to or is there a better/best practice way?

推荐答案

我可能会使用使用Subject的服务.这样,它既可以发布到订阅,也可以从订阅

I would probably use a service that uses a Subject. This way it can be both published to and subscribed from

import { Subject } from 'rxjs/Subject';

class SomeService {
  private _subject = new Subject<any>();

  newEvent(event) {
    this._subject.next(event);
  }

  get events$ () {
    return this._subject.asObservable();
  }
}

在您的组件中,一个可以发布,一个可以订阅

The from your components, one can publish and one can subscribe

@NgModule({
  providers: [ SomeService ]
})
class AppModule {}

@Component()
class ComponentOne {
  constructor(private service: SomeService) {}

  onClick() {
    service.newEvent('clicked!');
  }
}

@Component()
class ComponentTwo {
  constructor(private service: SomeService) {}

  ngOnInit() {
    this.service.events$.forEach(event => console.log(event));
  }
}

另请参见:

这篇关于如何在angular2中将功能从一个组件触发到另一个组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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