简体   繁体   中英

Angular: message-passing between components

I have a component A that handles a WebSocket. And in that I also have multiple components for presentation (eg B). When the WebSocket gets a specific message I need to do an action in a specific component (eg reload data).

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.component.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

@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)?

I think your approach is not "idiomatic" in Angular.

What is usually considered best practice is the following:

  1. create a service that exposes 2 types of APIs
  • normal methods that the clients of the service can use to issue commands
  • Observable streams for clients which need to subscribe to them
  1. pass the service to the components that need to use it via dependency injection

In your case the service should have probably something like this:

  • a method to start the connection with the websocket server (or maybe this connection is established at initialization of the service)
  • a private subject that you next when the appropriate message is received from the websocket service
  • a public Observable that you obtain executing the method asObservable() on the private subject

B.component.ts would receive the service via dependency injection and would subscribe to the public Observable exposed by the service.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM