0

I'm getting started with angular JS and there is something i don't really understand in a service i use :

(function () {

  angular
    .module('meanApp') // service qui dépend de ce module ?
    .factory('authentication', authentication);

  // $inject : To allow the minifiers to rename the function parameters and still be able to inject the right services, the function needs to be annotated with the $inject property. The $inject property is an array of service names to inject.
  // https://docs.angularjs.org/guide/di

  authentication.$inject = ['$http', '$window'];

  function authentication ($http, $window) {

    console.log("enters authentication service");
    var saveToken = function (token) {
      $window.localStorage['mean-token'] = token;
    };

    var getToken = function () {
      return $window.localStorage['mean-token'];
    };

    var isLoggedIn = function() {
      var token = getToken();
      var payload;

      if(token){
        payload = token.split('.')[1];
        payload = $window.atob(payload); //will decode a Base64 string
        payload = JSON.parse(payload);

        return payload.exp > Date.now() / 1000;
      } else {
        return false;
      }
    };

    var currentUser = function() {
      if(isLoggedIn()){
        var token = getToken();
        var payload = token.split('.')[1];
        payload = $window.atob(payload);
        payload = JSON.parse(payload);
        return {
          email : payload.email,
          name : payload.name
        };
      }
    };

    //An interface between the Angular app and the API, to call the login and register end-points and save the returned token. This will use the Angular $http service


    var register = function(user) {
      console.log("ARNAUD: Arriving in register promise");
      return $http.post('/api/register', user).success(function(data){
        saveToken(data.token);
      });
    };

    var login = function(user) {
      return $http.post('/api/login', user).success(function(data) {
        saveToken(data.token);
      });
    };

    var logout = function() {
      $window.localStorage.removeItem('mean-token');
    };


   // must return an object or function or at least a value from the factory
    return {
      currentUser : currentUser,
      saveToken : saveToken,
      getToken : getToken,
      isLoggedIn : isLoggedIn,
      register : register,
      login : login,
      logout : logout
    };

  }


})();

The functions declared above already return what i need and i just need to call them in my controller :

authentication.register(vm.credentials)

what is the exact purpose of

return {
  currentUser : currentUser,
  saveToken : saveToken,
  getToken : getToken,
  isLoggedIn : isLoggedIn,
  register : register,
  login : login,
  logout : logout
};

Maybe that's a stupid question to angular JS senior developers but that's not clear for me

Thanks for helping me to put some light on that

2 Answers2

0

A factory is a function that is called by angular, and that is supposed to return the instance of the service you want to make available to the application.

If you didn't return anything from the factory, it would effectively return undefined, and every time you inject the authentication service in your controllers, directives, etc., you would get undefined, instead of getting an object with methods.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

module.factory() will return an object -> for you to be able to call anything on that object you have to return it.

the other way would be to use module.service - this will return an instance.

module.service('test', function() {
  this.nice = function () {};
});

module.factory('test', function() {
  function something() {}
  return {
    nice: something
  };
});

factories are a lot more powerful than services - imagine the following:

module.fatory('prefix', function() {
  return function (prefix) {
    return {
      log: function (message) {
        console.log(prefix+': '+message;
      }
    };
  };
});
wodka
  • 1,320
  • 10
  • 20