在多个模块AngularJS中使用服务

时间:2017-09-10 17:56:26

标签: angularjs

我有两个应该连接的模块。 主模块,名为mainPage,有第二个模块,称为路由器,注入。它们位于不同的文件中。我想在mainPage和路由器中使用名为userPropagatorService的服务。 此服务应用于获取和设置当前登录的用户。 我试图向路由器模块注入服务,但是我收到了错误。 我怎样才能做到这一点?

mainPage文件:

var app = angular.module('mainPage',['reg','router']);

//Returns a promise which generates our user.
app.factory('userLoginService',['$http',function ($http){

   return{
     loginService: function(username,password){

        var info = {username:username, password:password}

        var user={};

        //Returning http request because of promises
        return $http({

            url: 'webapi/users/login',
            method: 'POST',
            data: info,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            transformRequest: function(obj) {
                var str = [];
                for(var p in obj)
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                return str.join("&");
            },
            data:{username: info.username, password: info.password}

        }).then(function (response)
        {

            user = response.data
            return user;

        });

    }
   }
}]);


app.service('userPropagatorService', function(){

   return{

       get:function(){

           return this.u;
       },

       set:function(user){

           this.u = user;

       }
   }

});

路由器文件:

var r = angular.module('router',['ngRoute'])
    .config(['$routeProvider', '$locationProvider','userPropagatorService',
        function($routeProvider, $locationProvider, userPropagatorService) {

        $locationProvider.html5Mode(true);

        $routeProvider
        .when("/home",{
            templateUrl: "pages/MainPage.html",
            controller:"homeController"
        })
        .when("/forums",{
            templateUrl: "pages/forumsPage.html",
            controller:"forumController"
        })
        .when("/topics",{
            templateUrl: "pages/topicsPage.html",
            controller:"topicsController"
        })
        .when("/comments",{
            templateUrl: "pages/commentsPage.html",
            controller:"commentsController"
        })
        .otherwise({
            redirectTo:"/home"
        });
    }])

    .controller("homeController",['$scope','$http',function($scope,$http){

        /*$http({
            url: "webapi/forums/all",
            method:"GET"
        })
        .then(function(response){
            console.log("YEA!");
            console.log(response.data);
        },
        function(response){
            console.log("NO:(");
        })*/

        $scope.username = "visitor!"
        $scope.user = userPropagatorService.get();
        if($scope.user != null){
            $scope.username=$scope.user.username + "!";
        }

    }])
    .controller("forumController",['$scope','$http',function($scope,$http){

        $scope.username = "visitor!"

    }])
    .controller("commentsController",['$scope','$http',function($scope,$http){

        $scope.username = "visitor!"

    }]);

2 个答案:

答案 0 :(得分:1)

如果您想使用userLoginService模块中的router,则需要将其从主应用中删除。

var app = angular.module('mainPage',['reg','router']);

angular.module("services",[])
  .factory('userLoginService',['$http',function ($http){

    return{ 
       //Service code here
    };
}]);

然后将其添加为router模块中的依赖项:

var r = angular.module('router',['ngRoute','services'])

答案 1 :(得分:0)

您无法注入Service" userPropagatorService"在配置块中。 使用$ method和return函数使其成为提供者。

ang.provider('userPropagatorService', function(){
    return{
            get:function(){
                        console.log("in get");
        },
            set:function(user){
          },
            $get: function(){
                    return {
                        meth1: function(){

                        }
                    }
             }
   }
});

ang.config(function(userPropagatorServiceProvider){
    console.log(userPropagatorServiceProvider.meth1())
})