Broadcast Service

O Broadcast Service facilita o envio de mensagens entre AngularJS e Angular2+ em aplicações construidas de forma hibrida com estas duas tecnologias.

Broadcast Service em Angular2+

class BroadcastService {
    subscribe(key:string, listner: (data?:any)=> void ) : () => void;
    emit(key:string, data?: any);
}

Broadcast Service em AngularJS

    {
        subscribe: function(key, listner),
        emit: function (key, data)
    }

O método subscribe subscreve todos os eventos para uma determinada chave (key). Quando é propagado um evento com essa chave, é executado a função de callback ("listner"). Este método returna uma função que ao ser executada remove a subscrição deste evento.

O método emit serve para propagar um evento para uma determinada chave ("key") e pode conter opcionalmente dados adicionais a serrem passados ("data").

O objectivo principal deste serviço é facilitar a comunicação entre Angular2+ e AngularJS, no entanto pode ser usado para comunicar entre vários componentes de Angular2+ e/ou de AngularJS.

Exemplo

O seguinte exemplo demonstra o envio de uma mensagem de Angular2+ para AngularJS e de AngularJS para Angular2+.

Angular2+


     class ExempleComponent {

         private unsubscribeBroadcastServiceFn: () => void;

         constructor(private broadcastService :BroadcastService) {
         }

         ngOnInit() {

            // subscribe events that will be broadcasted with key "message_from_angularjs"            
            let subscribeKey = "message_from_angularjs";
            let callbackFn = (data:string) => {
                console.log(data);
            }

            this.unsubscribeBroadcastServiceFn = this.broadcastService.subscribe(subscribeKey, callbackFn);


            // broadcast a message to anyone that is "listening" to broadcast with key "message_from_angular2+"
            this.broadcastService.emit("message_from_angular2+", "Test Message from angular2+");
         }

         ngOnDestroy(){

             // unsubscribe when the component is destroyed
             if(this.unsubscribeBroadcastServiceFn) {
                 this.unsubscribeBroadcastServiceFn();
                 this.unsubscribeBroadcastServiceFn = null;
             }
         }
     }

AngularJS


    module.controller("exampleController", ["$scope", "broadcastService", exampleController]);
    function exampleController($scope, broadcastService) {

        var unsubscribeBroadcastServiceFn = null;

        function init() {

            // subscribe 
            unsubscribeBroadcastServiceFn = broadcastService.subscribe("message_from_angular2+", function(data){
                console.log(data);
            });

            // unsubscribe when the controller is destroyed
            $scope.$on("$destroy", function(){
                if(unsubscribeBroadcastServiceFn !== undefined && unsubscribeBroadcastServiceFn !== null) {
                    unsubscribeBroadcastServiceFn();
                    unsubscribeBroadcastServiceFn = null;
                }
            });
        }

        init();
    }