0

I have seen angular services implementation in below two ways:

angular.module('my.service.MyService', []).service('MyService', function() {
        return {
            getMyDetails: getMyDetails,
        };
    function getMyDetails(filterParams) {
        return $http({
            method : 'get',
            data : JSON.stringify(filterParams),
            url : "/getMyList",
            headers : {
                'Content-Type' : 'application/json'
            }
        });
    }    
});

And

angular.module('my.service.MyService', []).service('MyService', function() {
        this.getMyDetails = function getMyDetails(filterParams) {
            return $http({
                method : 'get',
                data : JSON.stringify(filterParams),
                url : "/getMyList",
                headers : {
                    'Content-Type' : 'application/json'
                }
            });
        };
});

Is there any advantages of using one or another ? (e.g. Closures or memory leaks )

P. Moloney
  • 721
  • 8
  • 22
Hardik Mishra
  • 14,779
  • 9
  • 61
  • 96

1 Answers1

0

By looking at the docs. service('myService', F) invokes new F. So its more a question of JS than angularjs.

times = function (x) {return x*2}

F1 = function() {
  this.f = times
}

F2 = function() {
  return {
    f: times
  }
}

f1 = new F1
=> {f: f(x)}
f2 = new F2
=> {f: f(x)}

The difference is when you start messing around with prototypes

F1.prototype.x = 1
f1.x
=> 1

F2.prototype.x = 3
f2.x
=> undefined

So, as long as you don't change prototypes, it doesn't matter for angularjs. its probably safer to use the return format than the this.

Guy Yogev
  • 861
  • 5
  • 14