【问题标题】:Emitting event from root component to router outlet child component从根组件向路由器出口子组件发出事件
【发布时间】:2017-01-01 04:38:02
【问题描述】:

我有以下结构: app.component.html 包含以下组件:

<componentA>
<router-outlet></router-outlet>

我将componentB注入到router outlet,componentB有自己的router outlet。

<componentB><router-outlet></router-outlet></componentB>

我在 ComponentB 的路由器出口中注入了 componentC

<componentC>

我想从 ComponentA 向 ComponentC 发送一个事件。

我正在尝试使用服务来完成此操作,方法是将其注入发送事件的 ComponentA 中,而 ComponentC 正在通过注入的服务订阅事件。组件 C 未接收事件。

但是,如果我将 componentA 移动到 ComponentB 中,则事件会成功发送到 ComponentC。

当 ComponentA 位于 app.component.html 的根目录时,如何从 ComponentA 向 ComponentC 发出事件?

[更新]

我按照bidirectional service 上的示例进行操作,但仍未收到该事件。代码如下:

我的服务:

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

@Injectable()
export class MyService {
   private mySource = new Subject<string>();
   source$ = this.mySource.asObservable();
   sendEvent(stringParam: string) {
      this.mySource.next(stringParam);
   }
}

组件 A 发送事​​件

 this.myService.sendEvent("test");

组件 C 订阅并监听事件

this.subscription = this.myService.source$.subscribe(stringParam => {
  console.log('Received event: ' + stringParam);
});

我正在使用 Angular RC5。知道我缺少什么吗?

【问题讨论】:

  • 试试private mySource = new BehaviorSubject&lt;string&gt;();。发送组件可能在接收订阅之前发送。
  • 没有运气 :( 感谢您的帮助。我将稍微改变我的项目结构,消除组件 B 中的子路由器插座,这可能会解决我的问题。
  • 很难说没有更多细节。您是否在两个组件都提供了服务?它只能在祖先(或根)处提供,否则两个组件都会获得不同的实例。
  • 情况就是这样 :) 该服务是在 app.module 和我的一个组件中提供的。谢谢!

标签: angular


【解决方案1】:

起初,路由器不会将组件添加到&lt;router-outlet&gt;,而是使其成为兄弟。这是因为 ViewContainerRef.createComponent 的工作原理。

EventEmitter 发送的事件也不会冒泡,因此只能用于在使用(event)="doSomething()" 的子元素上添加事件处理程序。

共享服务通常适合您的情况。 更多详情见https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

【讨论】:

  • 我遇到了类似的问题,并通过共享服务解决了它。谢谢。
  • 如果子组件在多个地方使用并且需要在每个地方表现不同怎么办。我应该在孩子使用的父服务上放置某种接口吗?或者注入几个共享服务来处理行为的子集。
  • 这个小信息很难说清楚。您可以用不同的组件包装您的组件,并在包装​​器组件中提供服务的不同实现以注入子级。
猜你喜欢
  • 2016-07-06
  • 2021-02-12
  • 2021-07-26
  • 2018-02-07
  • 2018-09-30
  • 2021-10-31
  • 2020-10-06
  • 2019-11-03
  • 1970-01-01
相关资源
最近更新 更多