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 に答える