Search code examples
angularjsasp.net-mvcangularjs-factory

Returning result of a resolved promise from factory


I have an Angular app, which contains a menu that is defined in av MVC view. So the menu is not related to the routes in the app. In the menu controller, I would like to inject an object containing data about the current user. I will then loop this object to decide which menu items should be visible to the user.

The factory looks like this:

.factory('currentUser', ['currentUserResource', function (currentUserResource) {return currentUserResource.get()}]) 

The get method is a standard $resource GET method.

Problem is, the factory returns a promise which takes a short while to resolve. So in my controller, some of the menu items are processed before the promise is resolved, and aren't showing when they should show.

In my controller I inject 'currentUser', and then have tried using in these ways:

$scope.currentUser = currentUser.then(function (data){
  return data
});

$scope.currentUser = currentUser;

currentUser.then(function(data){
  $scope.currentUser = data;
});

Is there any way, without using routing resolve, I can make sure that currentUser is resolved before the controller is loaded, or atleast that it is resolved first thing the controller does?


Solution

  • Use the $promise property of the $resource object to delay the work of the controller.

    resourceObject.$promise.then ( function onFulfilled(object) {
        //Do work that needs fulFilled object
    }).catch (function onRejected(response) {
        console.log(response.status)
    });;
    

    If the the resourceObject has been resolved, the onFulfilled function will be execute immediately. If the resourceObject has not been resolved, the $q service will wait before invoking the onFulfilled function.

    It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.

    The Resource instances and collections have these additional properties:

    • $promise: the promise of the original server interaction that created this instance or collection.

      On success, the promise is resolved with the same resource instance or collection object, updated with data from server. This makes it easy to use in resolve section of $routeProvider.when() to defer view rendering until the resource(s) are loaded.

      On failure, the promise is rejected with the http response object, without the resource property.

    -- AngularJS $resource Service API Reference