如何在angular2中触发从一个组件到另一个组件的功能?

Rol*_*ndo 9 angular

我有两个组件componentA和componentB.他们都是sibbling,并且是componentMother的孩子.

我想这样做,当我点击componentA上的按钮时,它会触发componentB上的函数调用.

是使用具有可观察的服务并且使用componentA发出componentB订阅的事件或者是否有更好/最佳实践方式的方法?

Pau*_*tha 10

我可能会使用一个使用a的服务Subject.这样它既可以发布也可以订阅

import { Subject } from 'rxjs/Subject';

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

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

  get events$ () {
    return this._subject.asObservable();
  }
}
Run Code Online (Sandbox Code Playgroud)

您的组件可以发布,也可以订阅

@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));
  }
}
Run Code Online (Sandbox Code Playgroud)

也可以看看: