How to see coming resourse params in angular? - angularjs

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.

Related

How to pass an array of object as parameters in Restangular?

I have no idea how i can pass an array of object in Restangular. I've read their documentation. I found that they provided such as customGET, customPOST etc. But, i didn't see the right example that related to my case. For now, i want it to get data from an API that needs params as its filter.
1) Params
var filter = {
category: 1,
page: 1,
product: 20,
price_range: ['bt',1,150]
}
2) Services
getRawList: function(filter) {
return rawProducts.customGET('',filter).then(function(response) {
return response;
});
},
What i got was an Internal Server Error. Any idea how to tackle this error ?
When sending data to a web server, the data has to be a string. So, on this situation i need to convert the array property to string (which is price_range) before send it to the server as filter. This code solved my question.
getRawList: function(filter) {
return rawProducts.customGET('',{
category: filter.category,
page: filter.page,
product: filter.product,
price_range: JSON.stringify(filter.price_range)
}).then(function(response) {
return response;
});
}

Make GET call to REST service with parameters in Angular 2

I am trying to make a GET call to the YouTube Web API but I cannot figure out how to pass parameters using the http.get function. I have used fiddler and made sure the request is being made. I am currently getting a 400 error saying that I am missing a the parameter "Part". How can I modify my code to include the required parameters in my request?
private _url = 'https://www.googleapis.com/youtube/v3/';
private _key = '';
getPlaylistVideos(playlistId, pageToken){
var url = this._url + "playlistItems";
var options = { part: 'snippet', maxResults: 50, playlistId: playlistId, key: this._key, pageToken: pageToken }
return this.http.get(url, options);
}
You need to include the search params in to your request. I think this will work for you:
getPlaylistVideos(playlistId, pageToken) {
let url = `${this._url}playlistItems`,
options = { part: 'snippet', maxResults: 50, playlistId: playlistId, key: this._key, pageToken: pageToken },
params = URLSearchParams();
for (let key in options) params.set(key, options[key);
return this.http.get(url, {search: options});
}
You create the URLSearchParams using the set method you can find the full documentation here
Please have a look at the already asked & solved question regarding AngularJS & YouTube V3 API. See here thanks to #Sandeep Sukhija.
Anyhow, about the missing parameter part, add it to the request ex: part: 'snippet'
Example code :
function getPlaylistVideos(playlistId, pageToken) {
// pass the page token as a parameter to the API
$.get('https://www.googleapis.com/youtube/v3/playlistItems', { part: 'snippet', maxResults: 50, playlistId: playlistId, key: key, pageToken: pageToken })
}
How to use the part parameter
The part parameter is a required parameter for any API request that
retrieves or returns a resource. The parameter identifies one or more
top-level (non-nested) resource properties that should be included in
an API response. For example, a video resource has the following
parts:
snippet contentDetails fileDetails player processingDetails
recordingDetails statistics status suggestions topicDetails

REST AngularJS #resource parametrized request

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

How to inject user data in $resource call?

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

Add parameters to query string when using PUT method with Angular's $http

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

Resources