Search code examples
javascriptangularjsurl-routing

angular injecting resolve into controller logging undefined


I have the following resolve:

.state('posts', {
      url: '/posts/{id}',
      templateUrl: 'posts.html',
      controller: 'postsController as postsCtrl',
      resolve: {
        post: getSinglePostWrapper
      }
    })

and helper function

getSinglePostWrapper.$inject = ['postsService', '$stateParams'];
function getSinglePostWrapper(postsService, $stateParams) {
    return postsService.getSinglePost($stateParams.id);
}

and my controller looks like this:

angular.module('flapperNews')
.controller('postsController', postsController);

postsController.$inject = ['postsService', 'post'];

function postsController(postsService, post) { 
   var vm = this;
   vm.post = post;
   console.log(post); //undefined here
}

I'm getting an undefined "post" when I try to inject the post from the resolve. I tried logging the post in the getSinglePostWrapper function, and it logs the correct object. I seem to be losing some binding or something from the resolve to the controller.

posts service

angular.module('flapperNews')
.factory('postsService', postsService);

postsService.$inject = ['httpService'];

function postsService(httpService) {
  return {
        getSinglePost: getSinglePost
  }
  function getSinglePost(postId) {
        httpService.baseGet('/posts/' + postId)
        .then(function(data) {
            return data;
        }, function(data) {});
  }
}

httpservice

angular.module('httpService', [])
.factory('httpService', httpService);

httpService.$inject = ['$http', '$q'];

function httpService($http, $q) {
  return {
        baseGet: baseGet
  }
  function baseGet(url) {
        return $http.get(url).then(
                function (result) {
                    return result.data;
                },
                function (result) {
                    return $q.reject(result);
                }
        );
    }

}

and I've injected httpservice into the first place I declare the flapperNews module.

FYI- everything is working. Other http requests are fine. This one is fine too. It just doesn't inject the post into the controller.


Solution

  • Promise chain breaks here.

      function getSinglePost(postId) {
            httpService.baseGet('/posts/' + postId)
            .then(function(data) {
                return data;
            }, function(data) {});
      }
    

    You don't return the promise, hence post will be resolved to undefined before httpService.baseGet request has been finished.