Promise factory in Angular

New to Angular may be the misuse of promises. I have a factory that returns a promise:

.factory('myData', ['$http', '$q', function($http, $q) {
    var deferred = $q.defer();

    $http.get('/path/to/endpoint')
        .success(function(data) {
            deferred.resolve(data);
        })
        .error(function(err) {
            deferred.reject(err.what())
        });

    return deferred.promise;
}])

Now, if I enter my factory, I can use the promise:

.controller('myController', ['$scope', 'myData', function($scope, myData) {
    myData.then(function(result) {
        $scope.data = result;
    });
}]);

This is good, but I am starting to use it myDatain several places, and I do not want to write a new one .thenin every directive and controller in which I use the data. After the promise is resolved I don’t care, is there no way to make a myDatareturn of the promise if it is not resolved, but to return the result after it is completed?

To write it in another way, can it myDatabe simple .then resultafter permission, or do I need to write a new one each time .then?

+4
2

promises

, myData :

.factory('myData', ['$http', function($http) {
    return $http.get('/path/to/endpoint').then(function(req){
       return req.data;
    });
}]);

, , promises Angular... - , , Angular . , . , , , :

.factory('myData', ['$http', function($http) {
    var result = []; // initial result to return
    var p = $http.get('/path/to/endpoint').then(function(res){
       result.push.apply(result, res.data); // add all the items
    });
    result.then = p.then; // allow hooking on it
    return result; // return the array, initially empty
}]);

- :

.controller('myController', ['$scope', 'myData', function($scope, myData) {
    $scope.data = myData;
}]);

( ) , , myData.then, , , if .

?

, Angular 1.2 ( 1.3), , . , , Angular , . , , ngResource, .

+5

, / factory . , .

0

All Articles