My Technical Notes

Friday, 21 August 2015

Angular Deferred → Promise Snippet

The following is a snippet demonstration the Angular `$q` service use to create a "Deferred", which, in turn, is used to create a "promise" by calling its `promise` property:

Note that `$http.get` already returns a promise object, therefore you would not do this, but it is good for demonstration purposes.


app.factory('DataService', function ($http, $q, $log) {
    return {
        getData: function () {
            var d = $q.defer();

            $http.get('/DataService/GetData')
                .success(function (data) {
                    d.resolve(data);
                }).error(function () {
                    d.reject();
                });

            return d.promise;
        }
    };
});

To use this:


DataService.getData().then(function(data) {
    // do something with data here...
});

References

No comments: