Angular - decorate the service to get multiple instances

I have eventServiceone that will be used for several modules under one ngApp. It has standard use:

eventService.on('eventName');

The thing is, I want to decorate the function onso that the prefix eventNamewith some id, which is unique to the module that uses it.

I was thinking about using a decorator inside each phase of the module configuration, for example:

// App
var myApp = angular.module('myApp', ['eventServiceModule']);
myApp.config(function($provide, eventServiceProvider) {
    $provide.decorator('eventService', eventServiceProvider.decorateWithId(20));
});

// Decorator function (inside eventService)
decorateWithId: (moduleId) => {
    return ['$delegate',function ($delegate) {
           const originalOn = $delegate.on;
           const newEventing = {};

           newEventing.on = function(event) {
                arguments[0] = `${moduleId}_` + event;
                originalOn.apply($delegate, arguments);
           };

           return Object.assign(newEventing, $delegate);
        }
    ];
}

But apparently, each decorator receives a new decorator object instead of a new object with a unique identifier, as I had hoped.

Any way to fix this or a new approach to achieve this?

+4
source share

Source: https://habr.com/ru/post/1656956/


All Articles