0

Im going through one of the Pluralsight courses on AngularJS with MVC5 and one of the services has this as a return statement and it looks rather strange. Im not sure what this is doing

return {
    insertEmployee: insertEmployee,
    updateEmployee: updateEmployee,
    getEmployee:getEmployee

};

the insert/update/get names are names of methods in the service, but I dont understand the return statement. What is this doing?

bitshift
  • 6,026
  • 11
  • 44
  • 108

3 Answers3

3

It returns an object with those methods available, example:

var methods = {
    insertEmployee: insertEmployee,
    updateEmployee: updateEmployee,
    getEmployee:getEmployee
}

Now you can do:

methods.insertEmployee(); //etc...
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • Ok, that seems reasonable. Its just that ive not seen that syntax, including the example you give. I was not aware you could define a object like that in javascript. – bitshift Jul 15 '15 at 17:16
1

Actually calling a service/factory (Both can be used the same way actually, despite the fact they're not intended to work the same way.) is just calling a function. The function you defined.

If you do this :

Service :

var myfunction = function(){
 alert("hello");
}

Without any return you will not see this function in your controller.

Controller :

 myservice.myfunction(); will not work.

You need to return an object to be able to use the functions.

Service :

var myfunction = function(){
 alert("hello");
}

return {
  myfunction: myfunction;
}

This will allow you to use the service this way in your controller :

myservice.myfunction();

I usually prefer to use the object syntax in an other way, but this is just a matter of tastes :

Service :

var service = {};

service.myfunction = function(){
   alert("hello");
}

return service;

This will also allow you to use this syntax in the controller :

myservice.myfunction();

Hope it helped, if you have anymore question, feel free to ask.

Okazari
  • 4,597
  • 1
  • 15
  • 27
1

Actually you can understand it as AngularJS defines a factory like that. It just means: I want to expose the functions insertEmployee, updateEmployee, and getEmployee to the users of this factory.

Please refer to AngularJS: Service vs provider vs factory.

In this way, say, your factory name is myFactory, the usage is like:

angular.module('MyApp')
     .controller('MyCtrl', ['$scope', 'myFactory', function ($scope, myFactory) {
          myFactory.getEmployee();
  }]);
Community
  • 1
  • 1
Joy
  • 9,430
  • 11
  • 44
  • 95