简体   繁体   English

使用angularjs在控制器中注入服务

[英]Inject service in controllers using angularjs

I'm creating an app using angularjs, I have two controllers, and one service (all in separated files). 我正在使用angularjs创建一个应用程序,我有两个控制器和一个服务(均在单独的文件中)。 My problem is that I can't inject the service in the controllers. 我的问题是我无法在控制器中注入服务。 I used the service in the same file as the controller and it worked, but I want it in separated files to share data between controllers. 我在与控制器相同的文件中使用了该服务,并且可以正常工作,但是我希望它在单独的文件中在控制器之间共享数据。

This is one of my controllers 这是我的控制器之一

     var app = angular.module('cloudpear', ['ngRoute','ServiceUser']);

    app.controller('login',['$scope','$location','$window', function(ServiceUser,$scope,$location,$window){
.....
}]);

This is my service 这是我的服务

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

app.factory('ServiceUser',function(){
    var user=[];

    return{
        add: add,
        get: get
    }

    function add(item){
        user.push(item);
    }

    function get(){
        return user;
    }

    return user;
});

I get this error: 我收到此错误:

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.4-build.5327+sha.233f47b/ $injector/modulerr…20(https%3A%2F%2Fcode.angularjs.org%2Fsnapshot%2Fangular.min.js%3A22%3A179) 未捕获的错误:[$ injector:modulerr] http://errors.angularjs.org/1.6.4-build.5327+sha.233f47b/ $ injector / modulerr ... 20(https%3A%2F%2Fcode.angularjs.org% 2Fsnapshot%2Fangular.min.js%3A22%3A179)

Can you tell me what I'm doing wrong, I've searched everywhere and tried multiple solution, but nothing worked! 您能告诉我我做错了什么吗,我到处搜索并尝试了多种解决方案,但没有任何效果!

As you have define a separate module for service, you need to inject service module in the cloudpear module declaration. 为服务定义一个单独的模块后,需要在cloudpear模块声明中注入service模块。

var app = angular.module('cloudpear', ['ngRoute','service']); 
                                                 //^^^^^^^^^^ instead of ServiceUser

Then need to inject service in controller 然后需要在控制器中注入服务

app.controller('login',['ServiceUser', '$scope','$location','$window',function(ServiceUser, $scope,$location,$window){

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM