I am trying to download user reports using a User
$resource
. However, the returned result comes in an object like so: (weird)
{0: "n", 1: "a", 2: "m", 3: "e", 4: ",", 5: "e", 6: "m", 7: "a", 8: "i", 9: "l", 10: ",", 11: "p", 12: "a", 13: "r", 14: "t", 15: "n", 16: "e", 17: "r", 18: ",", 19: "r", 20: "o", 21: "l", 22: "e", 23: ",", 24: "p", 25: "h", 26: "o", 27: "n", 28: "e", 29: ",", 30: "s", 31: "t", 32: "a", 33: "t", 34: "u", 35: "s", 36: "↵", 37: "M", 38: "i", 39: "c", 40: "h", 41: "a", 42: "e", 43: "l", 44: " ", 45: "J", 46: "o", 47: "r", 48: "d", 49: "a", 50: "n", 51: ",", 52: "m", 53: "j", 54: "@", 55: "m", 56: "j", 57: ".", 58: "c", 59: "o", 60: "m", 61: ",", 62: ",", 63: "a", 64: "d", 65: "m", 66: "i", 67: "n", 68: ",", 69: "8", 70: "0", 71: "1", 72: "5", 73: "6", 74: "4", 75: "1", 76: "3", 77: "6", 78: "1", 79: ",", 80: "↵", $promise: Promise, $resolved: true}
When I use $http.get everything comes as expected:
name,email,partner,role,phone,status
Michael Jordan,mj@mj.com,,admin,8015641361,
I have no idea what I am doing wrong. Here are my files:
search.controller.js (with two approaches producing different results)
$scope.downloadReport = function() {
$http.get('/api/users/download',{params:$state.params}).success(function(res) {
console.log(res)
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(res),
target: '_blank',
download: 'filename.csv'
})[0].click();
});
User.download($state.params,function(res){
console.log(res)
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(res),
target: '_blank',
download: 'Users.csv'
})[0].click();
},function(err){
console.log(err)
});
};
user.service.js (tried with and without isArray)
angular.module('Raizzle.Admin')
.factory('User', function ($resource) {
return $resource('/api/users/:id/:controller', { id: '@_id'}, {
download: {
method: 'GET',
params: {
id:'download'
}
},
changePassword: {
method: 'PUT',
params: {
controller:'password'
}
},
get: {
method: 'GET',
params: {
id:'me'
}
}
});
});
I'm guessing that $resource has a hard time returning raw data? Any ideas?
Thanks in advance!
$resource assumes the response is a JSON object and does additional processing under that assumption. You have several options here to solve your problem:
Use transformResponse to avoid parsing to JSON object (see $resource documentation about transformResponse: https://docs.angularjs.org/api/ngResource/service/$resource ), not sure that would even work.
Use $http instead of $resource.
Make the backend return a JSON object instead of plaintext.