Use service in multiple modules AngularJS -
i have 2 modules should connected. main module, called mainpage has second module, called router, injected. in separate files. want use service called userpropagatorservice in mainpage , in router. service should used , set logged in user. tried inject service router module, errors. how can achieve this?
mainpage file:
var app = angular.module('mainpage',['reg','router']); //returns promise 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; } } });
router file:
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!" }]);
if want use userloginservice
in router
module, needs broken out of main app.
var app = angular.module('mainpage',['reg','router']); angular.module("services",[]) .factory('userloginservice',['$http',function ($http){ return{ //service code here }; }]);
then add dependency in router
module:
var r = angular.module('router',['ngroute','services'])
Comments
Post a Comment