2

I am following a tutorial on Angular Services and testing the below mentioned code. I am able to get the value in view from a TestService like -

TestService.name & TestService.$get()

but I want to know what if I need to get a value returned from the function like - return "From myFun"+this.name; in this case.

Code -

var myApp = angular.module('myApp', []);

myApp.controller('mainCtrl', function($scope, TestService){
    $scope.service = "Data From Service: "+TestService;
});

var myFun = function() {
    this.name = "FirstName";

    this.$get = function() {
        this.name = "Second Name";
        return "From $get: "+this.name;
    };

    return "From myFun"+this.name;
};

// A service returns an actual function
myApp.service('TestService', myFun);
Cœur
  • 37,241
  • 25
  • 195
  • 267
Tech Solvr
  • 505
  • 1
  • 7
  • 25

1 Answers1

1

Service

A service is a constructor function which creates the object using the new keyword. You can add properties and functions to a service object by using the this keyword. Unlike a factory, it doesn't return anything (it returns an object which contains method).

Service does place with this which is context of that service, and then return that context.

Simply word you can not return object from the service, you could do that using factory because factory does return an object.

Factory

var myApp = angular.module('myApp', []);

myApp.controller('mainCtrl', function($scope, TestService){
    $scope.service = "Data From Service: "+TestService;
});

var myFun = function() {
    var name = "FirstName";
    return "From myFun"+this.name;
};

// A service returns an actual function
myApp.factory('TestService', myFun);

But in above case you can only return one value at a time, for adding function you need to modify the object which you are going to return from the factory.

Modified Factory

var myApp = angular.module('myApp', []);

myApp.controller('mainCtrl', function($scope, TestService) {
    $scope.service = "Data From Service: " + TestService;
});

var myFun = function() {
    var TestService = {};
    TestService.name = "FirstName";
    TestService.get = function() {
        TestService.name = "Second Name";
        return "From myFun" + TestService.name;
    };
};

// A service returns an actual function
myApp.factory('TestService', myFun);

Working Plunkr

For more details read this answer where explained how service and factory are implemented.

Community
  • 1
  • 1
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299