Search code examples
single-spa-angularsingle-spa

Communicating single-spa container app to angular child app


I need a help to communicate from my container single-spa to loaded angular app ( child ). when user click on parent app ( spa-container ) option, that should communicated to child application to change the mode.

it will not happen very frequently. But not able to find a way to communicate from container to loaded angular application.

there is a detail given by spa itself : spa-communication detail but not clear and there is no detailed steps. any one help me?


Solution

  • I'm one of the maintainers of single-spa.

    We tend to be light on our opinions in the documentation about how to implement communication between modules because there are a lot of ways to implement it and each comes with pros/cons. In the situation you described it sounds like you might want to explore option #3 from the link you posted.

    Custom Browser events

    In the parent you fire custom events on the window. API on MDN.

    Quick example

    //  in the parent (usually called the single-spa config or root-config in the documentation)
    const event = new CustomEvent("myEvent", {favoriteMovie: 'StarWars'})
    window.dispatchEvent(event)
    
    // in the child (or registeredApplication)
    window.addEventListener("myEvent", myEventHandlingFunction)
    
    function myEventHandlingFunction(e) {...}
    

    That should at least get you started, there are other options for communication as well and this particular approach isn't going to be the best solution in every situation.

    It's also worth noting that customEvents don't work in IE11 unless you include a polyfill.