1

I'm calling a promise which returns an object in the service, but somehow gets lost in the controller.

From my controller I'm calling:

dataService.getSpanishOverviewByID(newItem, api) 
.then(getSpanishOverviewByIDSuccess)
.catch(errorCallback);

In my service it seems everything is working correctly:

function getSpanishOverviewByID(newItem, api) { 
console.log(newItem + " / " + api);
return $http({
  method: 'GET',
  url: '/api/' + api,
  newItem: newItem
})
.then(getSpanishByIDSuccess)
.catch(sendGetVolunteerError);
}


function getSpanishByIDSuccess(response) {
    var log = [];  
    angular.forEach(response.data, function(item, key) {
          console.log('I found this!' + response.config.newItem + " " + item.title);
          if(item.title == response.config.newItem){
            console.log('matching ' + item);
            this.push(item);
        }
    }, log);
    console.log(log);
    return log; 
  }

The console.log(log) returns an object: enter image description here

For some reason this does not get passed over to the controller correctly:

function getSpanishOverviewByIDSuccess(data) {
  $rootScope.newItem = data;
  console.log('brought back ' + data);
}

The console.log('brought back ' + data); returns:

brought back [object Object]

I'm not sure why this error might be occuring. It seems like the promise should pass off the data that is returned in the console.log(log);

1 Answer 1

6

This is a quirk of Javascript string concatenation. If you log an object by itself, the console will display the entire object in the friendly way you screenshotted above. However, if you log a string plus an object, the Javascript interpreter will cast the object as [object Object] instead of stringifying it properly. The object itself is probably still fine; the log statement is just giving you a typecast version of it.

The easiest solution here is this:

console.log('brought back');
console.log(data);

Or:

console.log('brought back', data);

Then your identifying string and your complete object with its visual hierarchy of properties will be logged separately, you'll avoid the string concatenation issue, and everything should look good.

Sign up to request clarification or add additional context in comments.

1 Comment

After some testing, it looks like a single statement will do if you use a comma instead of a plus sign: console.log('brought back', data);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.