Pregunta

I'm confused about how to create services and inject (use) them in my controllers. It seems it is very simple but I can't get my code to work. I'm stuck with this error:

Error: [$injector:unpr] Unknown provider: Flickr

I define the service:

angular.module('myApp.services', [])
.provider('Flickr', function(){
    // service code
})

Include it in my app module:

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

and then reference it in a controller:

app.controller('FlickrCtrl', ['$scope', '$routeParams', 'Flickr', function($scope, $routeParams, Flickr){
    // controller stuff
});

and reference the files at the bottom of index.html

<script src='js/app.js'></script>
<script src='js/config.js'></script>
<script src='js/services/Flickr.js'></script>
<script src='js/controllers/flickr.js'></script>

Why can't angular find the service I defined when I ask it to inject it into the controller?

¿Fue útil?

Solución

When using .provider, you are creating a provider that should return a configurable singleton. In many cases, this singleton is a singleton factory, spitting back an object that has services you can use.

First, you would need to refer to it as FlickrProvider instead of Flickr when you call it to set a config.

Without seeing more of your code, I can't tell if you're returning a new Flickr from your provider, which is what you would need to do in order to use a service instance in the way I think you're trying to do.

check out: http://docs.angularjs.org/guide/providers

Basically though, in order to inject and use Flickr like you are trying to do, you would need to do something like this:

.provider('Flickr',function FlickrProvider(){
    this.$get = function(){
         return new Flickr()
    }


})

function Flickr(){

    this.doSomething: function(){
         //do something or return something
    }

}

If you only want to define a service, and not make it a configurable provider, then use .factory instead, which will only need Flickr to be injected in order to be used.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top