YourReflection YourReflection - 1 year ago 64
AngularJS Question

Inject an object into a service function

I have been struggling with this for a few hours now without getting to a good solution. How can I inject an object into a function, so that I can use it in there? Example:

angular.module(moduleName).service('myService', MyService, MyObject);

Here, MyObject is defined, so everything is ok. But then, inside the function, it is undefined. How can I pass the object to the function and use it in there?

CamundaService.$inject = ['$http'];
function CamundaService($http, MyObject) {...}

Injecting it as a second parameter in the array did not work and I get an error:

angular.js:13708 Error: [$injector:unpr] Unknown provider

Any help is very much appreciated :)

Answer Source

You can use Angular constant:

var app = angular.module('myApp', []);

app.constant('MyObject', {
    message: 'hello world'

Now you can inject MyObject.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download