【发布时间】: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<string>();。发送组件可能在接收订阅之前发送。 -
没有运气 :( 感谢您的帮助。我将稍微改变我的项目结构,消除组件 B 中的子路由器插座,这可能会解决我的问题。
-
很难说没有更多细节。您是否在两个组件都提供了服务?它只能在祖先(或根)处提供,否则两个组件都会获得不同的实例。
-
情况就是这样 :) 该服务是在 app.module 和我的一个组件中提供的。谢谢!
标签: angular