Search code examples
javascriptangularjspromiseangularjs-service

How to create reset() method in Service that return promise?


I've got a service called MyArticles. Using $http GET, collects all articles for a given Category. The MyArticles Service is injected in ControllerA, ControllerB, ControllerC, that should run some commands after MyArticles Promise is resolved.

Works after first initialisation, but I don't know what to do if I need to reset() the loaded data for MyArticles, since the commands in the ControllerA, ControllerB, ControllerC only runs the first time, after the promise is resolved. For example, what if I'd like to get Articles from a different Category ?

I'm trying to find a pattern for this and I wrote the following, I guess it helps to understand what I'd like to achieve:

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

MyApp.config(function($locationProvider){

  $locationProvider.hashPrefix('!');

});

MyApp.factory('MyService', function($q,$timeout){

    var deferred;

    var loadData = function(){

        deferred = $q.defer();

        $timeout(function(){
            deferred.resolve({ 
                myData: "test"
            });
        }, 250);

    };

    return {

        reset: function(){

            loadData();

        },

        getPromise: function(){

            return deferred.promise;

        }

    };

});

MyApp.controller('MyCtrl', function($scope,MyService){

  $scope.foo = "Service share data";

  MyService.reset();

  MyService.getPromise().then(function(data){

        console.log(data);

  });

});

*the example is also available at: http://jsbin.com/OCaNehe/2/

I wonder what I can do, if I need a service - using promises - that should be able to refresh data and the service is being injected in different Controllers, etc ?

Thanks for looking!


Solution

  • Another alternative is to use watches. See: http://plnkr.co/edit/auovRxGPViyflUVPvG1A?p=preview. It might be easier to maintain compared to $emit/$broadcasts later on, especially if you end up having tons of services along with directives and controllers that use them.

    Also you might want to think about using the natural scope inheritance angular has, but that depends on your application.