Angular Resource not sending request to API - javascript

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!

Related

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.

AngularJS Resource with relation between tables

is this possible with AngularJS Resource?
/api/client/:id/jobs (get all the jobs from this client)
/api/client/:id/job/:jobId (get the job form this client)
My Factory:
.factory('Client', ['$resource', 'Api',
function ($resource, Api) {
var Client = $resource(Api.url() + 'client/:id/',
{
id: '#id'
},
{
'update' : { method: 'PUT', isArray: false }
}
);
return Client;
}
]);
Thanks!
I found a solution for my problem.
I have to create another factory to do the job:
.factory('ClientJobs', ['$resource', 'Api',
function ($resource, Api) {
var ClientJobs = $resource(Api.url() + 'client/:clientId/job/:jobId',
{
clientId: '#Id',
jobId: '#Id'
},
{
'query': { method: 'GET', isArray: true },
'update': { method: 'PUT' }
}
);
return ClientJobs;
}
]);
And, i can use the factory like this:
ClientJobs.save({clientId:clientId, jobId:job.id}, job, function (result) {
deferred.resolve(result);
}, function (reason) {
deferred.reject(reason);
});
Now, everything is working.
And for help those people who are working with UI-ROUTER, there is this question with an excellent answer about complex states like mine and nested views:
Nested Views with Nested States

Angularjs $resource response is not returning data

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

How to "rebuild" a $resource from a factory in angularjs?

I'm implementing my own API-Token system into my AngularJS-Laravel project, so the API-Token is sent over $http using headers. The thing is, when a user logs in, it sets the API token in the API factory, but the $resource doesn't get updated.
myApp.factory('Api', ['$resource', '$http', '$cookies',function($resource, $http, $cookies) {
var baseURL = 'an api url';
var APIToken = $cookies.token;
return {
SetToken: function(token) {
APIToken = token;
console.log(APIToken);
},
Authenticator: function(data,callback) {
$http({
url: baseURL + 'auth',
method: "GET",
params: data
}).success(callback);
},
Authors: $resource(baseURL + "journalists/:id", {id: '#id'}, {
update: {
method:'PUT',
headers: { 'API-Token': APIToken }
},
query: {
method:'GET',
isArray: true,
headers: { 'API-Token': APIToken }
}
}),
};
}]);
The most interesting part is the headers: { 'API-Token': APIToken } part. The problem is that when SetToken is called, the headers won't get updated. Is there any way around this? Am I using the wrong function for this?
Your $resource object is created and setup only once when it is called. It doesn't access the APIToken variable every time you make a call to one of its functions. In order to make the code above work, you would have to call SetToken() before you call Authors() because once you call Authors(), the $resource object is created and will use the value of APIToken at that moment. I don't know of any way to do what you want and still use the $resource service. You might have to just use the $http service directly, like you're doing for your Authenticator function.
Authors: {
update: function(obj){
$http({
url: baseURL + 'journalists/' + obj.id,
method: "PUT",
params: obj
});
},
query: function(obj){
$http({
url: baseURL + 'journalists/' + obj.id,
method: "GET",
params: obj
});
},
})
Or something like that. Hope that helps.

AngularJS $resource & cache factory

I have implemented angular $resource with custom functions and parameters as follows:-
.factory('CandidateService', ['$resource', function ($resource) {
return $resource("api/:action/:id", {},
{
'getCandidates': { method: "GET", params: { action: "Candidate" }, isArray: true },
'getCandidate': { method: 'GET', params: { action: "Candidate", id: "#id" } }
});
}]);
And I am consuming this in the controller as follows:-
.controller('Controller', ['CandidateService', function ($scope, CandidateService) {
$scope.candidateList = [];
CandidateService.getAll(function (data) {
$scope.candidateList = data;
});
}]);
This is working absolutely fine. Now I need to cache the data from the api into the CandidateService Factory so it is not loaded eveytime I move between the controllers.
So I thought i would do something as follows:-
.factory('CandidateService', ['$resource', function ($resource) {
var Api = $resource("api/:action/:id", {},
{
'getCandidates': { method: "GET", params: { action: "Candidate" }, isArray: true },
'getCandidate': { method: 'GET', params: { action: "Candidate", id: "#id" } }
});
var candidateDataLoaded = false;
var candidateData = [];
return {
getCandidates: function () {
if (!candidateDataLoaded) {
Api.getAll(function (data) {
angular.copy(data, candidateData);
});
}
return candidateData;
}
}
}]);
But I just cant get this to work. I think it has something to do with angular factory being a singleton.
Is my approach correct to implement the caching?
You can use the $cacheFactory object.
See : http://docs.angularjs.org/api/ng.$cacheFactory
You can cache $http request like that :
var $httpDefaultCache = $cacheFactory.get('$http');
If you want to retrieve a specific url in cache do :
var cachedData = $httpDefaultCache.get('http://myserver.com/foo/bar/123');
$You can clear the cache too :
$httpDefaultCache.remove('http://myserver.com/foo/bar/123');
or :
$httpDefaultCache.removeAll();
Complete post here : Power up $http with caching

Categories

Resources