Siavosh
Siavosh

Reputation: 2354

Pass Services to Application Config in angularjs

I am developing an application with angularjs I have this piece of code for checking if the user is logged in at the end of the routers I also define a function in a Service in order to have a function accessible in our controllers

Question:

How to have access to myFunction from MyService inside that run function ?

And how to make an ajax call inside the myFunction in myService? Actually I don't know how to pass $http parameter to MyService and how to pass MyFunction from MyService to MyApp run function.

   MyApp.config(function($routeProvider) {
       $routeProvider
       .when('/fooRoute', {
          templateUrl : 'fooURL',
          controller : 'fooController'
       })
   }).run(function( $rootScope, $location, $templateCache, $http) {
       if (signed_in == false) {
            $location.path("/login");                    
        } else {
           //Here I need to call the function of MyService
        }
  });

This is my Service code:

   MyApp.factory('MyService', function() {
    return {           
        myFunction : function() {

           //Here I need to make an ajax call

        }
      };
    });

Upvotes: 1

Views: 111

Answers (1)

Miraage
Miraage

Reputation: 3464

MyApp.factory('MyService', ['$http', function ($http) {
  return {
    myFunction: function () {

      //Here I need to make an ajax call
      $http.get()

    }
  };
}]);

// upd

.run(function($rootScope, $location, $templateCache, $http, MyService) {
    // your code
});

Upvotes: 1

Related Questions