0

Is there any way to make dependency injection inside ui-router resolve function?

I trying to achieve something like this:

resolve : {
    anArray : function(/* no dependencies yet */) {
        var currency = 'eur';

        //here I'd like to make a dependency injection
        var currencyDetail = /*injected dependency*/.get();
        return currencyDetail;
    }
}

In the original project I have a large array at currency and a long list of services like eurdata, usddata etc, many of them not always used in resolving anArray.

Tried $injector.get(currency + 'data') but not worked.

2 Answers 2

2

You can have $injector inject inside resolve function and ask for dependency to it

resolve : {
    anArray : ['$injector', function($injector) {
        var currency = 'eur';

        //here I'd like to make a dependency injection
        var currencyDetail = $injector.get(dependencyName);
        return currencyDetail;
    }]
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yep. I forgot to inject the $injector. Thanks.
2

You can use the usual array-notation:

resolve: {
  anArray: ['dependency', function(dependency) {
    var currency = 'eur';

     //here I'd like to make a dependency injection
     dependency.doSomething();

    var currencyDetail = /*injected dependency*/.get();
    return currencyDetail;
  }]
}

6 Comments

As I see, you directly injecting a dependency called dependency, but in my case I don't have any dependencies at that point. I want to inject them inside the function.
So, at what point would you have them? Do you dynamically create services? Are you loading them from a backend?
I have all the services created, but I don't want to inject all of them, just a fraction, based on currency.
Ah, okay. Then you could use Pankaj's answer. But bear in mind, that it wouldn't be minification safe. Use the array-notation to ensure minification safety.
@PankajParkar, yeah. I either missed it, or you edited your answer. Anyways, it's correct now
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.