Angularjs $resource response is not returning data - javascript

I am trying this with $resource I have a service Post
app.factory('Post', function ($resource, $cookieStore) {
return $resource('http://localhost:port/posts/:id', {"id":"#id", port:':9000'}, {
query: { method:'GET', isArray: true , headers: {'X-AUTH-TOKEN':'authToken='+$cookieStore.get("authToken")}},
save: { method:'POST',headers: {'X-AUTH-TOKEN':'authToken='+$cookieStore.get("authToken")}},
update: {method:'PUT' ,headers: {'X-AUTH-TOKEN':'authToken='+$cookieStore.get("authToken")}},
delete : {method: 'DELETE',headers: {'X-AUTH-TOKEN':'authToken='+$cookieStore.get("authToken")}},
get : { method: 'GET', headers: {'X-AUTH-TOKEN':'authToken='+$cookieStore.get("authToken")}}
});
});
And the in the controller I am trying to get all the posts.
Post.query(function(data){
console.log(data.length);
console.log(data)
});
I was expecting the data to be whats returned from the server but the console.log is showing me this how can I get the access to the actual json data from server?
3 posts.js:18
[Resource, Resource, Resource, $promise: Object, $resolved: true]
0: Resource
1: Resource
2: Resource
$promise: Object
$resolved: true
length: 3
__proto__: Array[0]

According to documentation it seems that first parameter in action is parameter object for query and only then success callback. So try:
Post.query({}, function(data) {
console.log(data.length);
console.log(data);
})
You also can use $promise:
Post.query({}).$promise.then((function(data) {
console.log(data.length);
console.log(data);
})

Related

Angular JSON post only sending one item of json array

I wrote an angular quiz and I'm trying to send the quiz results to the database for processing. My $http call is as follows:
function saveQuiz() {
quizObj.isSaving = true;
var data = {
id: quiz_id,
action: 'quiz_data',
part: 'save_quiz',
score: quizObj.score,
passed: quizObj.passed,
completed: quizObj.completed,
percentage: quizObj.perc,
time_spent: $filter('formatTimer')(quizObj.counter),
questions: quizObj.quiz.questions
};
console.log(data);
$http({
url: quizapp.ajax_url,
method: "POST",
params: data
})
.then(function(response) {
console.log(response.data);
quizObj.isSaving = false;
},
function(response) { // optional
// failed
console.log(response);
});
}
Notice I am passing an array of json questions as quizObj.quiz.questions.
The problem on the server side is that $_POST['questions'] evaluates to the last item of the quizObj.quiz.questions json object instead of the full list.
Where have I gone wrong?
When using the $http service through Angular, data goes with method: "POST" and params goes with method: "GET"
Change the properties on your config object you are passing to the $http service like so:
$http({
url: quizapp.ajax_url,
method: "POST",
data: data // <-- data here, not params since using POST
}).then(function () { /*...*/ }));

ngResource.myfunc().$promise.then returns empty array

I'm using angularjs-1.5.0 to write my application.
I created a service that uses a $resource to fetch data from the api server. the service is called MyApi.
(function () {
angular.module('myalcoholist').factory('MyApi', ['$resource', '$auth', function ($resource, $auth) {
return $resource('https://myalcoholist.com:8888/drink/:cmd',
null, {
pouringSpeedTypes: {
method: 'GET',
params: {api_token: $auth.getToken(), cmd: 'get_pouring_speed_types'},
isArray: true
},
pouringLocationTypes: {
method: 'GET',
params: {api_token: $auth.getToken(), cmd: 'get_pouring_location_types'},
isArray: true
}
});
});
}]);
})();
and in my controller i use this service using the following code:
MyApi.pouringLocationTypes().$promise.then(function(data) {
console.info(data);
});
MyApi.pouringSpeedTypes().$promise.then(function (data) {
console.info(data);
});
the problem is that the data is.. a promise i guess.
this is what data contains:
$promise: d
$resolved: true
length: 0
__proto__: Array[0]
what do I do with that? how do I get the actual data from the get request ?
thank you for your comments, you allowed me to pinpoint the issue.
first of all I didn't update my server's code that's why when you tried these addresses you got Method not Allowed.
the problem that i've been having is that these requests really returned empty arrays.
so first of all my API returns a json Object not an array so i changed isArray to false.
so after that and actually fixing my API Server, this is what I received:
$promise: d
$resolved: true
data: Array[4]
success: true
my API server returns a json with data and success. so things are working now! thanks a lot.

Angular Resource not sending request to API

I am writing a basic CRUD Angular app of sorts and have been using $resource throughout. The issue is that when I am trying to issue a get request to an API endpoint I am getting an error in resource:
[Log] Object (job-detail.js, line 30)
config: Object
headers: Object
method: "GET"
transformRequest: Array[1]
transformResponse: Array[1]
url: "http://127.0.0.1:8000/estimators/1"
__proto__: Object
data: null
headers: function (name) {
get arguments: function () {
get caller: function () {
length: 1
name: ""
prototype: Object
set arguments: function () {
set caller: function () {
__proto__: function () {
status: 0
statusText: ""
__proto__: Object
I have no idea what is going wrong because I have tested that URL and it works fine. Also, I have used $resource in the exact same fashion, just on a different endpoint and it is working fine. Lastly, $resource isn't even sending the request, on my API it's not logging any requests to the endpoint. I am at a loss, here is the relevant code:
angular.module('lincorFeApp.controllers')
.controller('JobDetailCtrl', ['$scope', '$routeParams', 'Estimator', '$location',
function($scope, $routeParams, Estimator, $location) {
getEstimator();
function getEstimator() {
$scope.estimator = Estimator.get({ pk : $scope.job.estimator }, function() {
console.log($scope.estimator.name);
}, function(response) {
console.log(response);
});
}
}
]);
and in services.js:
myApp.factory('Estimator', function($resource) {
return $resource('http://127.0.0.1:8000/estimators/:pk', { pk : '#pk' }, {
update : { method: 'PUT' },
delete : { method: 'DELETE' }
});
});
Any help would be greatly appreciated!

AngularJS referencing associative array or object after returning from service

I'm new to AngularJS (and primarily a PHP Dev) and am trying to pull data back from a service into my controller and then reference that array/object. I get the data back from $http fine and can reference it just fine inside the service but once I return it back to the controller for the life of me I can not figure out how to get at the data.
Here's the service call:
app.factory('ProfileData', ['$http', function($http){
var myProfile = Array();
return {
getData: function(empl_id_in,scope){
$http({
method: 'post',
url: 'api/userprofile.php',
params: {
empl_id: empl_id_in
}
}).then(function(data, status, headers, config){
if(data['data']['success']){
myProfile.push(data['data']);
}
else {
console.log("Error");
}
}).catch(function(err){
console.log("Error");
$location.path('/login');
});
return myProfile;}
And here's where I try to pull it back in my controller:
var profileData2 = Array();
profileData2.push(ProfileData.getData($scope.first));
console.log(profileData2);
The console.log returns this:
[Array[0]
0: Array[1]
0: Object
cube: "S32-3411-M1"
first: "Joe"
last: "Blow"
success: 1
title: "Programmer Analyst Lead"
proto: Object
length: 1
proto: Array[0]
length: 1
proto: Array[0]
If I try to reference this like this: console.log(profileData2[0][0]["cube"]) I get errors or undefined. I've tried making everything an object (instead of an array) and get the same problem. How should I be referencing this??
Edit: Here's my response from PHP call:
$response=array("success"=>1,"first"=>$first,"last"=>$last,"title"=>$title,"cube"=>$cube);echo json_encode($response);
Yes, JavaScript does a lot of stuff asynchronously.
app.factory('ProfileData', ['$http', function($http){
var myProfile = Array();
return {
getData: function(empl_id_in,scope){
//return promise returned by $http
return $http({
method: 'post',
url: 'api/userprofile.php',
params: {
empl_id: empl_id_in
}
});
}
}
});
ProfileData.getData($scope.first).then( function(data) {
profileData2.push(data);
});

AngularJS tokenWrapper - wrong callback arguments

AngularJS 1.2.1
ngResource 1.2.1
I got the weirdest problem.
I'm using tokenWrapper by Andy Joslin (AngularJS: How to send auth token with $resource requests?)
I have a resource defined like that:
.factory('someService', ['$resource', 'api_host', 'TokenHandler',
function($resource, api_host, TokenHandler) {
var Resource = $resource(api_host + 'applicant/:command/:xxx', { xxx: '#xxx', command: '#command' }, {
'get': { method: 'GET', isArray: false },
'save': { method: 'POST', isArray: false },
'create': { method: 'put', isArray: false },
'message': { method: 'post', isArray: false }
});
Resource = TokenHandler.wrapActions( Resource,
["query", "get", "save", "remove", "create", "message"] );
return Resource;
}])
its wrapped by tokenHandler and token is sent with every request and thats great.
the problem is with invoking the error callback.
when using the resource like that
var interview = new someService({ command: 'doSomething', xxx: $scope.xxx});
interview.$create({}, function(response) {
console.log(response);
}, function(e) {
alert('error');
});
The Problem
When the resource returns 200 the success function (1st argument) is invoked as it should.
When the resource returns something else, the error callback is not invoked.
I've tried to log the tokenHandler and it seems like the handler is massing up the arguments.
var tokenWrapper = function( resource, action ) {
// copy original action
resource['_' + action] = resource[action];
// create new action wrapping the original and sending token
resource[action] = function( data, success, error){
console.log(success, 'success');
console.log(error, 'error');
return resource['_' + action](
angular.extend({}, data || {}, {token: tokenHandler.get()}),
success,
error
);
};
};
the result of the console.log prints out the data as success and success as error.
how can I fix that?!
angular 1.2.0 changed the way promises are handled. and this look like a promise issue (you are not getting the expected order of suceess``failure```. see this for an example. my guess that insisting on using resource from 1.5 doesn't work we'll with this behavior, so you are not getting the expected data. yes. there are error messages when upgrading. but solving them shouldn't take long.

Categories

Resources