byrdr byrdr - 5 months ago 32
AngularJS Question

Angular.js promise returning [Object object]

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);

Answer

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.

Comments