简体   繁体   中英

Promise in meanjs app controller “then” is not a function

In my meanjs app created using meanjs generator and auto generated CRUD-module, for income below, I want to customize the promise returned by the get method so that I can call methods and do transformations on the retrieved data. So i attempt to change it in my controller:

// Find existing Income
    $scope.findOne = function() {
        Incomes.get({
            incomeId: $stateParams.incomeId
    }).then(function(income){
       $scope.income = income;
       $scope.incomeDollar= income*$scope.dollarRate;
    });

This only gives me the error : undefined is not a function, and pointing on then. What am i doing wrong here? How can I do transformations on the data retrieved from the get method above?

The pattern i am trying to use is in the end of the article here . I want to switch from the short version to the long so that i can do more stuff in my callback.

// LONG:

myModule.controller('HelloCtrl', function($scope, HelloWorld) {

  HelloWorld.getMessages().then(function(messages) {
    $scope.messages = messages;
  });

});

To simplify this, the writer of the article place the promise returned by 'getMessages' on the scope:

// SHORTER:

myModule.controller('HelloCtrl', function($scope, HelloWorld) {

  $scope.messages = HelloWorld.getMessages();

});

The promise object can be accessed using $promise. From the doc

The Resource instances and collection 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...

So, your code should look like:

// Find existing Income
$scope.findOne = function() {
    Incomes.get({
        incomeId: $stateParams.incomeId
}).$promise.then(function(income){
   $scope.income = income;
   $scope.incomeDollar= income*$scope.dollarRate;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM