0

I have 2 modules that should be connected. The main module, called mainPage has the second module, called router, injected. They are in separate files. I want to use my service called userPropagatorService in mainPage and in router. This service should be used to get and set currently logged in user. I tried to inject service to router module, but I get errors. How can I achieve this?

mainPage file:

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;

       }
   }

});

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!"

    }]);
3
  • There are couple of things, those I suspected. 1. userLoginService is part of mainPage module. so it won't be available inside router(I'd suggest you to create a separte common module which will have common component) 2. Service/factory won't be injected inside config block, you could consider creating provider rather than service(it depends of what kind of situation you're dealing with. Perhaps you could use resolve so that you can use service) Commented Sep 10, 2017 at 18:17
  • Services can not be injected in config blocks. From the Docs: Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured. For more information see, AngularJS Developer Guide - Module Loading & Dependencies. Commented Sep 10, 2017 at 18:50
  • @PankajParkar I can not use provider, it is not helpful at all. I tried creating a common module, but still, other modules cant see propagatorService. Commented Sep 10, 2017 at 19:06

2 Answers 2

1

If you want to use the userLoginService in the router module, it needs to be broken out of the main app.

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

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

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

Then add it as a dependency in the router module:

var r = angular.module('router',['ngRoute','services'])
Sign up to request clarification or add additional context in comments.

2 Comments

Does this apply for userPropagatorService too?
Yes with the caveat that it can't be used in config blocks.
0

You cant inject Service "userPropagatorService" in config block. Make it a provider with $method and return function from there .

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())
})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.