Parker Song
Parker Song

Reputation: 151

Promise 'then' is not a function when using the 'ui-router'

the config:

.state('index.usermng.userInfo',{
        url: '/userInfo/:id',
        templateUrl: 'tpls/userInfo.html',
        controller: 'userInfoCtrl',
        resolve: {
            userInfo: function($http, serverUrl, $stateParams){
                return $http.get(serverUrl + "/user/info?userId=" + $stateParams.id);
            }
        }
    })

the controller:

//UsrInfo Controller
userApp.controller('userInfoCtrl', ['$scope', 'userInfo', function($scope, userInfo) {
userInfo.then(function(response) {
    $scope.data = response.data
})

I defined the 'userInfo' in the 'ui-router' config.js,when i want to use it in the controller,causing 'then' of undefined

Upvotes: 0

Views: 1628

Answers (2)

Razvan B.
Razvan B.

Reputation: 6771

Firstly, your resolve should be:

From $routeParams docs:

Note that the $routeParams are only updated after a route change completes successfully. This means that you cannot rely on $routeParams being correct in route resolve functions. Instead you can use $route.current.params to access the new route's parameters.

So just inject $route instead of $routeParams:

resolve: {
    userInfo: function($http, serverUrl,  $route){
      return $http.get(serverUrl + "/user/info?userId=" + $route.current.params.id)
      .then(function(response){
        return response.data;
      })
    }
}

This way, the resolve function returns you the response , so in your controller, you can have:

$scope.data = userInfo

More on promise

If your resolve function returns you a promise (which is not in your case), it can be accessed using $promise.

Promise Example (using $resource)

.factory('userInfo', ['serverUrl', '$resource', function (serverURL, $resource) {
    return $resource(serverUrl + '/user/info?userId=');
}]);

From the doc

On success, the promise is resolved with the same resource instance or collection object, updated with data from server...

So in this case, in your controller should be:

userInfo.$promise.then(function(response) {
    $scope.data = response
})

Upvotes: 2

Miles P
Miles P

Reputation: 710

This is how I setup my resolves, see if this works for you:

resolve: {
    userInfo: function($http, serverUrl, $stateParams){
        return $http.get(serverUrl + "/user/info?userId=" + $stateParams.id).then(function(response){
return response.data});
    }
}

Then in your controller userInfo is resolved and you won't need to wait for it to resolve.

Upvotes: 1

Related Questions