In the following post I will show how to implement pub/sub in an NgUpgrade application.
NgUpgrade is the bridge between the old world and the new world. Basically it allows code from Angular 1.x to live in the same app as code written in newer versions of Angular.
In my view, the recommended approach when using NgUpgrade is to downgrade new Angular code and embed it in existing Angular 1.x code. Technically, you can also go in the opposite direction by upgrading Angular 1.x code. However, I see this as somewhat counter productive if the goal is to eventually phase out the Angular 1.x code.
It's important to point out that the downgrade process does not convert your code to Angular 1.x code. The “downgraded” code will still execute in the context of new Angular. This is true for both components and services.
In the following example I will show how to implement RxJs based Pub/Sub between a legacy Angular 1.x component and a downgraded Angular 2+ component.
The key to this is exercise using a downgraded Angular 2+ service. Registering the service as an NgModule level provider ensures that both components will share the same service reference. Sharing the same instance is important since it allows for shared state.
First lets take a look at the shared service.
If you are familiar with RxJs you will recognize this as a typical Subject based Pub/Sub service.
There is no trace of Angular 1.x here since this service will in all cases execute in the context of Angular 2+. Even when it's embedded in the Angular 1.x component.
Angular 2+ Component
The Angular 2+ component is also pretty standard. It injects an instance of the Pub/Sub service.
Angular 1.x Component
Next up is the controller of the Angular 1.x component.
As you can tell, the same Pub/Sub service is injected into the legacy component. How does Angular know to inject the service into the old Angular world?
This is where NgUpgrade works its magic.
You downgrade the service by running the following NgUpgrade code:
Pretty cool that we can make the service compatible with Angular 1.x with just a few lines of code, right?
The service now exits in both Angular worlds, but it's important to remember that it only executes in the context of the new world. This makes state sharing much easier since we are not dealing with two different instances.
If you emit a message from one component, it will be picked up by the other component. Basically the components subscribe to each others messages. I added a filter to ensure that the components don't react to their own messages.
If you register the service as a provider at the NgModule level it will be created as a singleton across both worlds. In both cases we use DI to inject the service, but the same instance is injected in both components.
Keep in mind you will break the sharing if you register the service at the component level in the Angular 2+ component though.