Skip to content Skip to sidebar Skip to footer

Angular Service Created Function Needs This Keyword

While the question is more I suppose javascript type question more so than an Angular question, I was creating a service in which I would call it like this // controller injects a

Solution 1:

If you are writing a factory make use of an object inside the factory ,and put all your calls into it.like

(function() {
    'use strict';

    angular
        .module('app')
        .factory('activityApi', activityApi);

    activityApi.$inject = ['$http'];

    functionactivityApi($http) {
        var service = {
              getActivityById : getActivityById ,
        };
        return service;


     functiongetActivityById(id) {
        $http.get('/Umbraco/Api/ActivityApi/GetActivity').
          success(function(data, status, headers, config) {
           console.log(data);
           return data;
        }).
       error(function(data, status, headers, config) {
          // logerror
       });
    };

    };
})();

here you are returning factory object in which calling function is available.

Here you can call the factory function as

var activities = activityApi.getActivityById(1122);

Solution 2:

Regarding angular's services and factories. Both .service and .factory return functions. However, angular's $injector calls the function returned by .service with new keyword (using $instantiate method), whereas it calls .factory function as is using invoke method. Since it uses new keyword for service functions, you have to have this keyword inside your function to reference the object, created by new and returned from the function.

As @NikhilVM shows, you can use factory instead of service if you want to avoid using this. Both service and factory return values are cached, so if the factory returns an object it becomes global. So in this sense it's no different from service using this to add methods. Using factory has the advantage in that you can return a function constructor to be later called to instantiate multiple class instances, while you can't do that with .service.

Post a Comment for "Angular Service Created Function Needs This Keyword"