【发布时间】:2019-04-28 20:16:34
【问题描述】:
我已经创建了 2 个组件和一个服务,如下所示,
组件交互.service.ts
@Injectable()
export class ComponentInteractionService {
public dataSubject = new BehaviorSubject<string>("Test");
getTestData(): Observable<any> {
return this.dataSubject.asObservable();
}
pustTestData(dataToPush: string): void {
this.dataSubject.next(dataToPush);
}
}
first.component.ts
export class FirstComponent {
constructor(private componentInteractionService: ComponentInteractionService) {
componentInteractionService.getTestData().subscribe(data=> {
console.log("Received at 1 -- " + data);
});
}
sendTestData(): void {
this.componentInteractionService.pustTestData("sending data from 1");
}
}
second.component.ts
export class SecondComponent {
constructor(private componentInteractionService: ComponentInteractionService) {
componentInteractionService.getTestData().subscribe(data=> {
console.log("Received at 2 -- " + data);
});
}
}
我目前面临的问题是
在页面加载时,两个组件订阅者都被触发,但是当我使用 FirstComponent 中的 sendTestData() 方法推送数据时,只有 FirstComponent 正在被触发。 SecondComponent 中的订阅者没有被触发。 我应该怎么做才能让两个订阅者在使用 sendTestData() 方法推送数据时被触发?
我的控制台日志如下..
1 点收到——测试
2 点收到 -- 测试
在 1 接收——从 1 发送数据
预期输出..
1 点收到——测试
2 点收到 -- 测试
在 1 接收——从 1 发送数据
在 2 接收——从 1 发送数据
【问题讨论】:
-
尝试调用
ngOnInit()而不是constrcutor() -
我试过这个,但仍然面临同样的问题。
-
为什么要创建单独的函数?您可以直接使用
dataSubject,像这样:this.componentInteractionService.dataSubject.subscribe(x=> { console.log(x)});并在您的ngOnInit中调用它。 -
您能创建一个 stackblitz 示例来重现您的问题吗?
-
注意:推送数据方法在第二个组件中是不可见的。您已经在 dataSubject 上创建了 behaviorSubject,因此您将收到数据
标签: angular observable angular6 behaviorsubject