I'm using $resource to fetch json data from a backend server.
First, I get a list of ids, with a first resource call. Then, for each id received, I use $resource to fetch data associated with this id.
Now, the problem is : I would like to associate the response with the id sent, so I can record data into a hashtable. (eg: $scope.table[response.id] = data; ). The only way I've found, is to have the API send back the id in the json response, but I'd like to associate the id with the query, so I know for which id is the response I got, without having the API to send it back.
Here is my current code (simplified, just to get the idea) :
// the factory. eg I send /rest/item/12345
app.factory('Item', function ($resource) {
return $resource("/rest/item/:id", { id: '#id'})
});
// the call (in a loop)
// I need to get { "id" : 12345, "text" : "blahblahblah" }
Item.get({ id : itemId },
function(data){
$scope.table[data.id] = data;
});
I would like to write something like this :
// the call (in a loop).
// I would like to only need to get { "text" : "blahblahblah" }
Item.get({ id : itemId },
function(id, data){
$scope.table[id] = data;
});
I guess I could use this form :
$scope.table[itemId] = Item.get({id : itemId});
But I need $scope.table[itemId] to be a "correct" value all the time, not a promise, and I want it to be updated just when I receive the answer.
Is it possible ?
something like this might work:
// get the array of ids
ItemIds.get({},
function(ids){
// for each id, make the request for the actual item
ids.forEach(function(id) {
Item.get({ id : id },
function(data){
// in this nested callback, you have access to data and id
$scope.table[id] = data;
});
});
});
Related
I have next WEB API:
GET List<EventHistory> '/service/eventhistories'
GET EventHistory '/service/eventhistories/{id}'
DELETE EventHistory '/service/eventhistories/{id}'
PUT EventHistory '/service/eventhistories'
POST EventHistory '/service/eventhistories'
Using angular i want use #resource to get information from server.
angularApp.factory('eventHistoryFactory', function ($resource) {
return $resource('/inner/service/eventhistories/:id',{id:'#id'});
});
But using this declaration i do not have any API to request the page based on some data.
var pageRequest = {
size: size,
page: page
};
or to send update for eventHistory entity.
Based on OP's comment:
Say you want to update a single entity:
.controller('someCtrl', function($stateParams, eventHistoryFactory){
//For the sake of the demonstration - id comes from the state's params.
var eventHistory = eventHistoryFactory.get({id: $stateParams.id});
eventHistory.$promise.then(function(){
//Modify the entity when HTTP GET is complete
eventHistory.address = 'New York';
//Post the entity
eventHistory.$save();
//If you wish to use PUT instead of POST you should declare that
//in the class methods of $resource
});
//Another example using query
var entries = eventHistoryFactory.query({
page: 0,
size: 20,
before: Date.now()
});
//This is translated into GET /inner/service/eventhistories?page=0&size=20&before=111111111111
//and should be interpreted correctly by your backend.
entries.$promise.then(function(){
//entries now contain 20 first event history with date earlier than now.
var specificEntry = entries[0];
//Same deal - modify the entity when HTTP GET is complete
specificEntry.address = 'New York';
//Post the entity
specificEntry.$save();
});
the first answer seems good, but i think this way more understandable and simply for begginers:
eventHistoryFactory.get(pageRequest, function (returnData) {
console.trace('request processed successfully: ' + returnData);
params.total(returnData.totalElements);
$defer.resolve(returnData.content);
}, function (error) {
console.log('request processed with error: ' + error);
})
to make page request in dynamic way the object should be build before request from ngTable current properties (use ngTable API).
Please pay your attention to eventHistoryFactory. It does not have parameter for pageRequest object, but it works -angular magic. By GET request in url you can see:
?page=2&size=25
I'm using Angular's $http service to make web api requests. When I use the GET method, the two param values are added to the query string:
// http://foo.com/api/test?heroId=123&power=Death+ray
$http.get("/api/test", {
params: { heroId: 123, power : "Death ray" }
})
However, when I use the PUT method the params are JSON-encoded and sent as the request payload:
// {"params":{"heroId":123,"power":"Death ray"}}
$http.put("/api/test", {
params: { heroId: 123, power : "Death ray" }
})
How can I force the params to be added to the query string when using PUT?
With $http.put, $http.post or $http.patch, the config object containing your url parameters goes as the third argument, the second argument being the request body:
$http.put("/api/test", // 1. url
{}, // 2. request body
{ params: { heroId: 123, power : "Death ray" } } // 3. config object
);
$http.put documentation for reference
AngularJS send json data and not x-www-form-urlencoded format data.
Though you can try the below one:
$http.put("/api/test", { heroId: 123, power : "Death ray" });
If your api url is "api/test/heroId/power",
var data = 123+'/Death ray'
$http.put("api/test"+data);
I am trying to pull JSON data and display on my console just to see if its working. I am seeing an error message.
I am trying to fetch a Model with id 1:
var TeamModel = Backbone.Model.extend({
urlRoot: '/json/team.json'
});
//Create Team Model Instance with id of team
var teamModel = new TeamModel({
id: 1
});
//Fetch the json data
teamModel.fetch();
var director = teamModel.get('name');
Here is the JSON file :
{
"id" : 1,
"name" : "Sam",
"img_small" : "images/sam.jpg",
"location" : "NYC",
"role" : "Director, Producer, & Writer",
}
This yields the following error :
GET http://localhost:9000/json/team.json/1 404 (Not Found)
You should use url, not urlRoot:
var TeamModel = Backbone.Model.extend({
url: '/json/team.json'
});
Backbone uses urlRoot to generate resource URLs based on the operation you perform (fetch, save, delete) and Model id. When you fetch a single Model, the URL it generates is urlRoot + '/' + id.
Therefore when you attempt to fetch a Model with id 1, the constructed URL is /json/team.json/1
If you set url, however, Backbone always uses that url. It does not change it based on operation or model attributes. This is the behaviour that you need, because you have a single static resource.
I am using the $httpBackend to mock a backend and I want to get access to the headers when I have a request:
$httpBackend.whenPOST('/movies').respond(function(method, url, data) {
// How do I get access to the headers.
// I want to check the headers and retrieve a token.
var params = angular.fromJson(data),
movie = MoviesDataModel.addOne(params),
movieId = movie.id; // get the id of the new resource to populate the Location field
return [201, movie, { Location: '/movies/' + movieId }];
});
Basically, I want to check a value from the headers before I send the data.
Any ideas on how to do it?
Got this from the manual
httpBackend.whenPOST('/movies',data, function(headers){
return headers['Authorization'] == 'xxx';
})
.respond(function(method, url, data) {
I have a query
$scope.product_detail = Source1.get({
FirmId: $routeParams.firmId,
ProductId: id
});
With this query come a resourse :
Resource { $get=function(), $save=function(), $query=function(), more...}
How to see the properties of this resourse, for example $scope.product_detail.id, coz console.log($scope.product_detail.id) give me 'undefined' ?
I think you are trying to display it before it is available. You can make it display the data in the success callback.
$scope.product_detail = Source1.get({
FirmId: $routeParams.firmId,
ProductId: id },
function(resource) {
console.log(resource.product_detail.id);
});
This resource's get method is asynchronous. Assuming your REST back-end returns {id: 123}, it will be available on product_detail as soon as your REST response is received.
If you try to access it immediately after you call get, you won't see your values because they haven't been received yet.
The get function can take a success and error callback:
Source1.get({}, function(response) {}, function(error){});
The value of response will be the same reference as $scope.product_detail, so the callbacks are unnecessary... unless you want to execute code specifically on return.