Get object by id using $resource - javascript

I am dealing with a little issue, and need some help.
I have an API setup, works just fine.
Now I want to get a single object using its ID. I have tried using $http, but could't get it to work. So I switched back to $resource. Here is what I have in my service file.
getPlatesInSelectedContainer: function() {
return $resource('/api/v1/platesincontainer/:id', {id: "#id" },{
get: { cache: true, method: 'GET' }
});
},
And in controller I am reaching to function doing so.
CleaningPlatesFactory.getPlatesInSelectedContainer({id : 1}, function(data){
$scope.plates = data;
console.log(data);
})
But this is not returning any results. What I am doing wrong?
UPDATE
Earlier I have tried $http but getting this.

I would still get $http to work. It's as simple as this:
getPlatesInSelectedContainer: function(data) {
return $http.get('/api/v1/platesincontainer/' + data.id);
}
You need to accept the data object in your service function.

Inside the service:
getPlatesInSelectedContainer: function(data) {
return $resource('/api/v1/platesincontainer/:id', {id: data.id },{
get: { cache: true, method: 'GET' }
});
}
Then call it like this:
getPlatesInSelectedContainer({ id: 123 })

Related

Angular 1.x: $resource JSON is returning as a weird object

I have been working with $resource for a little bit now, however it seems tricky to use with JSON return values. I have tried many solutions but it seems to always return it as an object with..less than desirable output as shown in the image below.
When I verify the data is postman I receive something like this:
{
"examples": [
{
"text": "their pet cat"
}
],
...
With this I know the data is being sent properly. However, every solution I try for getting the data back correctly using $resource gives me the weird object you saw in the image above.
I have tried many but I believe these are closest:
Attempt One:
jsonpquery: { method: 'JSONP', params: {callback: 'JSON_CALLBACK'}, isArray: true }
Attempt Two
return $resource('myBackend.php?action=word',
{}, {
query: { method: "GET", isArray: false }
});
Attempt 3:
return $resource('myBackend.php?action=word',
{ get: { method: "JSON", isArray: false}});
This is in a factory and I call it like so:
dictionaryFactory.getWord('cat')
.query().$promise.then(function(value) {
console.log('value value', typeof value);
console.log('value value', value);
});
I am fairly sure I am not setting up my $resource return function correctly
but after a few days of searching and trying solutions on the web I assume I am not understanding how to do it.
I have tried the answers from this post and was unable to solve the issue. The data comes back the same.
Update: I have now tried this as well:
query: {
method: 'GET',
isArray: true,
transformResponse: function(data) {
return angular.fromJson(data).items;
}
}
However this just gives me the following error in console:
Unexpected number in JSON at position 7305 at JSON.parse
I know the data is not the problem as I am using the API From Oxford: https://developer.oxforddictionaries.com/d
Update:
I read some more and tried this however I get am error
Unexpected number in JSON at position 7305
:
return $resource('myBackend.php?action=word', {},
{
jsonpquery: {
method: 'get',
dataType: 'json',
transformResponse: function(data, headers){
return JSON.parse(data);
}
}
});
I also tried this however for some reason then I get a 403. Which I do not understand as when it is a get request it will return the weird object of characters.
return $resource('backend.php?action=oxford', {} {
jsonpquery: {
method: 'JSON',
isArray: true
}
});

How to get value from $http function in angularjs

I've create a function in angular. And it is working fine and can get correct result but my problem is i want particular node from result. i have worked with JSON and Jquery, but i am new in angular.
This is my code.
$scope.booking= function(docid,addid){
//console.log(addid);
var a = $http({
method: 'POST',
url: "http://localhost:81/DoctorStayServiceAngular/model/getDoctorBookingDetail.php",
params:{"doctorid":docid,"addressid":addid,"day":weekday[d.getDay()]}
//params:{"doctorid":docid}
}).then(function mySucces(response) {
//$scope.count= response.data;
/*$scope.appo=[];
$scope.appo= i;
i++;*/
//
//console.clear();
return response.data;
});
console.log(a);
return a;
};
http://localhost:81/DoctorStayServiceAngular/model/getDoctorBookingDetail.php
return following json.
{
"status":"success",
"message":"",
"booking":{
"booking_detail":[{
"session":null,
"slot":null,
"day":"Friday"
}]
}
}
This how i can see in firebug
Expanded view
so i want to get value(which I've highlighted in image) from response(which is under $$state), what should i do?
in short how can i get bottom result?
{
"status":"success",
"message":"",
"booking":{
"booking_detail": [{
"session":null,
"slot":null,
"day":"Friday"
}]
}
}
$http service returns a promise(this is printed in your console logs), which will be resolved after that http call is complete.
Please go through this $q documentation on how deferred data works.
https://docs.angularjs.org/api/ng/service/$q
This should work,
$scope.booking= function(docid,addid){
$http({
method: 'POST',
url: "http://localhost:81/DoctorStayServiceAngular/model/getDoctorBookingDetail.php",
params:{"doctorid":docid,"addressid":addid,"day":weekday[d.getDay()]}
//params:{"doctorid":docid}
}).then(function mySucces(response) {
$scope.responseData = response.data;
});
};
After this you can bind the data in responseData to your view.

Populate select tag with $ngresource promise Angularjs

I have a select on page that i want to populate with data which i get from a server. I'm using service to retrieve this records but how can I access to those values from promise and put them in ng-option of select tag?
Get data from resource:
$scope.categories = Category.all({sorting:"asc"});
Resource:
factory('Category', function ($resource) {
return $resource('api/categories/:id', {}, {
all: {method: "GET", isArray: true, params: {sorting: '#sorting'}},
update: {
method: "PUT",
params: {
id: "#id"
}
}
})
}).
The call to Category.all() should return an array that will be filled with the retrieved values when the respective http request returns. If you want to run some code on completion, you can pass a callback like this:
$scope.categories = Category.all({sorting:"asc"}, function() {
// do something with the $scope.categories
});
You can also obtain a promise like this:
$scope.categories = Category.all({sorting:"asc"})
.$promise.then(function(categories) {
// do something with the categories
});

AngularJS 1.x How do I use resource to fetch an array of results?

This is what I wrote in my factories.js:
app.factory('CustomerCompany', function($resource){
return $resource('/customer_companies/:id.json', {id: "#_id"}, {
'query':{method: 'GET', isArray:false},
'getByCustomerAccount':{
method: 'GET',
params: {customer_account_id: customer_account_id},
isArray:true,
url:'/customer_companies/get_by_account/:customer_account_id.json'
}
});
});
Because I want to fetch a list of customer_companies that belong to a particular customer_account so I need to supply a customer_account_id.
In my controllers.js,
app.controller('customerAccountEditController', function($scope, CustomerCompany) {
$scope.data = {};
var path = $location.path();
var pathSplit = path.split('/');
$scope.id = pathSplit[pathSplit.length-1];
var customer_account_id = $scope.id;
$scope.list_of_companies = [];
CustomerCompany.getByCustomerAccount({customer_account_id: customer_account_id}, function(data){
console.log(data);
//$scope.list_of_delegates.push(data);
});
});
I get a customer_account_id not defined.
Where did I go wrong?
I think you don't need to define params inside your $resource & then URL will becomes url:'/customer_companies/get_by_account/customer_account_id.json' & while calling a method you need to pass the customer_account_id, from {customer_account_id: customer_account_id} so that it would create an URL with customer_account_id=2 somtehing like that.
Service
'getByCustomerAccount':{
method: 'GET',
//params: {customer_account_id: customer_account_id}, //removed it
isArray:true,
url:'/customer_companies/get_by_account/:customer_account_id'
}
Controller
CustomerCompany.getByCustomerAccount({customer_account_id: customer_account_id + '.json'}, function(data){
console.log(data);
//$scope.list_of_delegates.push(data);
});
This worked for me.
controllers.js
CustomerCompany.getByCustomerAccount({customer_account_id: customer_account_id}, function(data){
console.log(data);
//$scope.list_of_delegates.push(data);
});
services.js
app.factory('CustomerCompany', function($resource){
return $resource('/customer_companies/:id.json', {id: "#_id"}, {
'query':{method: 'GET', isArray:false},
'getByCustomerAccount':{
method: 'GET',
isArray:false,
url:'/customer_accounts/:customer_account_id/customer_companies.json'
}
});
});
What I changed:
on the server side, I decided to use /customer_accounts/:customer_account_id/customer_companies to render the results.
I realized that the data returned is always in object form, so I changed isArray in the $resource to false.
I pass the params like the way the Pankaj Parkar suggested in the controller when I call getByCustomerAccount
params: {customer_account_id: customer_account_id},
The customer_account_id you try to assign here is not defined.
Try params: {customer_account_id: '#customer_account_id'},

Angular $resource JSON Callback not working - is this best practice?

I'm creating a resource to pass data into my controller for an existing api that need to hook into. I am not able to modify the back end unfortunately.
My Resource factory currently looks like this:
'use strict';
angular.module('XXX')
.factory('elements', function (
$resource
) {
return $resource('http://XXX/api/v1/elements/:id',
{
callback: 'JSON_CALLBACK',
id: '#id'
},
{
query: {
method: 'JSONP',
params: {
id: '#id'
}
},
all: {
method: 'JSONP',
params: {}
}
}
);
});
The elements.query() works fine, however the elements.all() does not work unfortunately. I did notice that in the returned content in my network tab, begins with angular.callbacks._2([{... DATA...}]) - this doesn't seem right to me.
UPDATE.....
OK so i've got it working with this:
angular.module('XXX')
.factory('element', function (
$resource
) {
return $resource('http://XXX/api/v1/elements/:id',
{
id: '#id',
callback : 'JSON_CALLBACK',
},
{
query: {
method: 'JSONP',
params: {
id: '#id'
}
},
all: {
method: 'JSONP',
isArray: true,
params: {
callback : 'JSON_CALLBACK',
}
}
}
);
});
however the json that it returns to the console comes in as an array.. I am able to parse it for use, but just wondering now if this is best practice?
That is the way isArray is meant for.
You need the isArray flag, because angular has to create an empty Object - in this case an Array - before the request is sent. So all bindings will work, because you have the same reference. At the time the result has arrived, it will be populated to your variable, the result object / array.
We are doing the service calls like this, maybe it will help you:
.factory('Person', function($resource, AppConfig) {
var Person = $resource(AppConfig.remoteURL + '/person/:id', {}, {
query: {method:'GET'},
queryAll: {method:'GET', isArray: true},
create: {method:'POST'},
update: {method: 'PUT'}});
return Person;
});
and call it like this:
Person.queryAll(function (result) {
angular.isArray(result); // should be true
}, function (error)
{
//doh!
}
You might want to specify a custom transformResponse to convert pull the data out of the array form.
Snippet from $resource docs:
transformResponse – {function(data, headersGetter)|Array.<function(data, headersGetter)>} – transform function or an array of such functions. The transform function takes the http response body and headers and returns its transformed (typically deserialized) version.
So your code would be something along the lines of:
all: {
method: 'JSONP',
isArray: true,
params: {
callback : 'JSON_CALLBACK',
},
transformResponse: function(data, headersGetter) {
return data.[....].DATA;
}
}
Usually, $resource is used for RESTful APIs. JSONP only uses GET.
So, I would use $http.JSONP instead of $resource for this.
In your code, can you let your server-side support CORS?

Categories