[英]Angular: message-passing between components
I have a component A that handles a WebSocket.我有一个处理 WebSocket 的组件 A。 And in that I also have multiple components for presentation (eg B).并且我也有多个用于演示的组件(例如 B)。 When the WebSocket gets a specific message I need to do an action in a specific component (eg reload data).当 WebSocket 收到特定消息时,我需要在特定组件中执行操作(例如重新加载数据)。
The way I do this is having a subject in A. This is passed into B. When the WebSocket in A gets a message I call "next" to trigger B.我这样做的方式是在 A 中有一个主题。这将传递给 B。当 A 中的 WebSocket 收到一条消息时,我调用“next”来触发 B。
A.component.ts组件.ts
subj : Subject <string> = new Subject <string> ();
connectWebsocket ()
{
let sjs = new SockJS ("http://localhost:8090/ep");
this.sc = Stomp.over (sjs);
this.sc.connect ({}, (frame) =>
{
this.sc.subscribe ("/broker/webclient", (event) =>
{
if (event.body == "RELOAD")
{
this.subj.next ("RELOAD"); // trigger B to reload
}
});
}
}
B.component.ts B.component.ts
@Input () subj : Subject <string>;
ngOnInit ()
{
this.subj.subscribe
(
(msg) =>
{
// reload data if msg == "RELOAD"
}
);
}
Its working well.它运作良好。 But I am not sure if it is common strategy to do that or are there better ways (eg reload in A and pass only the data to B - or using another mechanism)?但我不确定这样做是否是常见的策略,或者是否有更好的方法(例如在 A 中重新加载并仅将数据传递给 B - 或使用其他机制)?
I think your approach is not "idiomatic" in Angular.我认为您的方法在 Angular 中不是“惯用的”。
What is usually considered best practice is the following:通常认为最佳实践如下:
In your case the service should have probably something like this:在你的情况下,服务应该有可能是这样的:
next
when the appropriate message is received from the websocket service当从 websocket 服务接收到适当的消息时,您next
的私人主题asObservable()
on the private subject一个公共的 Observable,您可以在私有主体上执行asObservable()
方法B.component.ts
would receive the service via dependency injection and would subscribe to the public Observable exposed by the service. B.component.ts
将通过依赖注入接收服务,并订阅服务公开的公共 Observable。
This idea is described in details in this article .这个想法在这篇文章中有详细描述。 Even if the article show an example in React, the concepts of Service and Component can be mapped one to one with those of Angular.即使文章展示了 React 中的示例,Service 和 Component 的概念也可以与 Angular 的概念一一对应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.