Search code examples
angularjsangular-promisedeferred

$q Promise in UI-Router Resolve?


Actually, this question can be simplified to "Return an $http or Restangular call result in a promise". My goal is to have a promise object that is resolved after an $http call completes:

var deferredCall= $q.defer();

Then this is resolved from the call:

$http.get (url)
   .then(function(result){ deferredCall.resolve('Success' + result);},
    function(){ deferredCall.resolve('Failure' + error););

Then I have a promise object that will be resolved when the call is complete (either succeeding or failing), this is what I want:

deferredCall.promise.then(function (value) {
    return //something to pass to controller;
});

The goal is that the controller is instantiated whether the resolve succeds or fails. My problem? Resolve can only take a promise, so: `deferredCall.promise. How do I resolve this promise with the call above withing the Resolve / through a service? Are the results of a service method a promise?

Like if I make a service whose method makes the $http call and then returns deferredCall?


Solution

  • This is how we resolve data in our project:

    Angular $routeProvider:

    $routeProvider
        .when('/something/something', {
            templateUrl: 'somewhere/some-details.html',
            controller : SomeController,
            resolve : {
                someItem : function (SomeService) {
                    return SomeService.getSomethingAll();
                }
            }
        })
    

    Controller:

    var SomeController = function ($scope, someItem) {};
    

    Data Service:

    .service('SomeService', function (SomeUtils, $http) {
        return {
            getSomethingAll : function () {
                return SomeUtils.promiseHttpResult($http.get("api/something/all"));
            }
        }
    })
    

    Utils Service:

    .service("SomeUtils", function($q) {
        return {
            promiseHttpResult: function (httpPromise) {
                var deferred = $q.defer();
                httpPromise.success(function (data) {
                    deferred.resolve(data);
                }).error(function () {
                    deferred.reject(arguments);
                });
                return deferred.promise;
            }
        }
    })
    

    Nice and simple. No skills required :) (DD)