1

我对如何创建服务并在我的控制器中注入(使用)它们感到困惑。看起来这很简单,但我无法让我的代码工作。我被这个错误困住了:

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

我定义服务:

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

将其包含在我的应用程序模块中:

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

然后在控制器中引用它:

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

并引用底部的文件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>

当我要求将其注入控制器时,为什么 Angular 找不到我定义的服务?

4

1 回答 1

1

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.

于 2014-03-09T10:18:54.790 回答