Conditional injection of a service in AngularJS
Asked Answered
I

3

5

I have defined a service like this :

angular.module('myApp').service('myService', [
'$rootScope',
...
...

I want my service to be instantiated only for new user (i.e. when user.createdAt > today).

So is there a way to conditionally inject my service or at least destroy my service without any side effect if the user is an old one.

Insurgence answered 31/12, 2014 at 13:2 Comment(0)
P
8

You can use the $injector service to get inject-ibles dynamically if you need to:

app.controller('DemoCtrl', function($injector) {
  this.clicky = function() {
    myFact = $injector.get('myFactory');
    myFact();
  };
});

app.factory('myFactory', function() {
  return function() {
    alert('foobar!');
  };
});

Here's a full running demo: http://jsbin.com/bemakemaja/1/edit

And the $injector docs: https://docs.angularjs.org/api/auto/service/$injector

As a general guideline though I'd recommend not designing your services such that simply injecting them has side effects.

Pippa answered 31/12, 2014 at 13:18 Comment(0)
C
0

use factory instead of service, so that you can have some checking logic in your service

angular.module('myApp').factory('myService', function () {

    if (newUser) {
        return { // your service implementation here
        }
    }
    return undefined;
};
Carbohydrate answered 31/12, 2014 at 13:10 Comment(0)
F
0

So is there a way to conditionally inject my service or at least destroy my service without any side effect if the user is an old one.

Best to capture this logic inside the service:

class Service{
    static $inject = ['$rootScope'];
    constructor($rootScope){
        if (user.createdAt > today){ /*something*/ }
        else {/*other thing*/}
    }
}

NOTE: services are singletons so conditional injection doesn't see like a desirable solution. Also to learn about $inject : https://www.youtube.com/watch?v=Yis8m3BdnEM

Feminize answered 31/12, 2014 at 17:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.