Why did my object lose its link after the promise?

I have a function that takes a named object issue

and then calls a promise. Any changes made to the object reference prior to fulfilling the promise will be reflected in the original reference. Any changes made after it are not. Why not and how can I fix it?

This example below shows the problem

angular.module('app').controller('IssueCtrl',['issues', function(issues){
   var issue = {};
   issue.id=1;
   issues.add_comment('test', issue).then(function(issue){
       console.log(issue.id);
   }
   // returns 'a'
}
]);


angular.module('app').factory('issues', function(){
  o.add_comment = function (comment, issue) {
      // Changes made before promise are reflected in original promise
      issue.id='a'
    return o.update(comment).then(function(new_comment){
      // Changes made after promise are not reflected in original promise
      issue.id = 'b'
      return new_comment
  }

  o.update=function(){
      // more code
  }
 return o;
});

      

+3


source to share


2 answers


When you call

issues.add_comment(issue);

      

this function ends with



return o.update(comment).then(...

      

which returns the promise immediately, not after fulfillment then()

. If you want to wait for this, you should do this in your initial appeal:

issues.add_comment(issue).then(....

      

+1


source


The problem is that the line in your controller is:

issues.add_comment('test', issue).then(function(issue){
   console.log(issue.id);
}

      

The service returns the promise object and eventually new_comment

. you are overwriting the original issue

in the function signature. Try something like this:



issues.add_comment('test', issue).then(function(resp){
   console.log('inside then', issue.id);
   console.log('then response', resp);
})

      

Working example

+1


source







All Articles