Is it possible to use repeating params in ngResours query - javascript

I'm using Angular with ngResource and i've got an api url:
GET http://my.com/rest/items?inState=TRANSIENT&inState=FINAL
How could I do query with two (not uniq) params 'inState'?
This is my Resource factory:
.factory('Resource', function ($resource, REST_URL) {
return {
items: $resource(REST_URL + 'rest/items',
{},
{
get: {method: "GET", params: {inState: '#inState'}}
})
};
})
And this is the way I'm call it:
//GET http://my.com/rest/items?inState=TRANSIENT
Resource.items.get({inState: 'TRANSIENT'}, function (data) {
//...
}, function (responce) {
//...
});
This is works but the problem is in how I'm send params - as object: {inState: 'TRANSIENT'}
I cannot write something like
{inState: 'TRANSIENT', inState: 'FINAL'}
beacuse of fields must be uniq
P.S. I know that it may be done with $http.

That's how to do this:
{inState: ['TRANSIENT', 'FINAL']
Example:
//GET http://my.com/rest/items?inState=TRANSIENT&inState=FINAL
Resource.items.getHistory({inState: ['TRANSIENT', 'FINAL']}, function (data) {
//...
}, function (responce) {
//...
});

Not sure if you have control over what is consuming the parameters, but if you do you could try passing the parameters as an object with an array of objects in it, like this:
{ states : [{inState : 'TRANSIENT'}, {inState : 'FINAL'}]}
Then just iterate through the states array and check each inState property.

Related

Send a list of parameters in angular and change route

I trying to call other route in angular, similar this
$location.path($scope.productPath+"/approveProducts/").search({ids});
I want send the list of ids to other controller but the ids are sending by url
http://localhost:8080/#/product?ids=1130&ids=1132&ids=7428&ids=15574&ids=15579&ids=15580&ids=6798968768697789
I need send ids similar a post requisition, not in a url, because i have a many ids in my call
How i do this in angular, send parameters and change my route to other controller?
I believe a better approach might be to utilize the angularjs service/factory to persist your data.
example:
.service('AngularJsService', function() {
var listOfIds = [];
return {
saveData: function(theIdsToSave) {
listOfIds = theIdsToSave;
},
getData: function () {
return listOfIds;
}
}
}
.controller('OriginatingController', function($location, AngularJsService) {
function navigateToTargetController() {
AngularJsService.saveData([1,2,3,4]);
$location.path('pathToTargetController');
}
}
.controller('TargetController', function($location, AngularJsService) {
function retrieveData() {
var ids = AngularJsService.getData();
// ids = [1,2,3,4]
}
}
You can use $http for send your params and then change your route
var req = {
method: 'POST',
url: 'http://example.com',// address for sending ids
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){
// this you can to change your url
$location.path($scope.productPath+"/approveProducts/");
}, function(){...});

get Alfresco.util.Ajax.request response.json data from external function

I have an alfresco webscript who return a json response.
I have a js function getWorkflowRepositoryContent() who call this webscript and get the data retuned in the response.
I store the response.json in an array list.
All works fine for me, but when i call getWorkflowRepositoryContent() from another js function, it returned an empty array when it must return an array containing the data received from webscript response.
There is the function where i return the data received from the webscript.
Can you tell me what i made a mistake, or tell me how to properly return the data from that function.
function getWorkflowRepositoryContent(){
var list=[];
var workflowFilesNameAndNodeRef;
var test=function getWorkflowFilesList(response)
{
workflowFilesNameAndNodeRef=response.json.nodes;
$.each(response.json.nodes,function(index,value){
list.push(value.name);
});
}
Alfresco.util.Ajax.request(
{
method:Alfresco.util.Ajax.GET,
url: Alfresco.constants.PROXY_URI + "/ALFRESCO-DIRECTORY",
successCallback:
{
fn:test,
scope:this
},
failureCallback:
{
fn: function(response)
{
Alfresco.util.PopupManager.displayMessage({text:"Failure"});
},
scope: this
}
});
console.log(list.length);
return list;
}
Your getWorkflowRepositoryContent is getting asynchronous data but returning synchronously so your example won't work.
An easy way would be to simple call your function with a callback argument.
function getWorkflowRepositoryContent(cb){ // pass a callback as an argument
var list=[];
var workflowFilesNameAndNodeRef;
var test=function getWorkflowFilesList(response)
{
workflowFilesNameAndNodeRef=response.json.nodes;
console.log(response.json.nodes);
$.each(response.json.nodes,function(index,value){
list.push(value.name);
});
$.each(list,function(index, fileName){
$('<option/>').val(fileName).html(fileName).appendTo('#saveButton');
$('<option/>').val(fileName).html(fileName).appendTo('#loadButton');
});
cb(list); // call the callback once the work is done
}
Alfresco.util.Ajax.request(
{
method:Alfresco.util.Ajax.GET,
url: Alfresco.constants.PROXY_URI + "/ALFRESCO-DIRECTORY",
successCallback:
{
fn:test,
scope:this
},
failureCallback:
{
fn: function(response)
{
Alfresco.util.PopupManager.displayMessage({text:"Failure To get StarXpert Workflow content"});
},
scope: this
}
});
}
getWorkflowRepositoryContent( function(list) {
console.log(list);
});
You could also use promises but it might be a little harder if you're not familiar with them.

How do you search and return a specific index of a JSON resource in AngularJS?

I have a json file of events setup like this:
{
2: {
sched_conf_id: "38",
title: "Coffee Break",
},
3: {
sched_conf_id: "39",
title: "registration",
},
}
I setup and angular factory like this:
.factory('eventFactory', ['$resource',
function($resource) {
return {
query: function(event_id) {
return $resource('/assets/events.json', {}, {
query: { method: 'GET', params: {id:event_id}, isArray: false }
}).query();
}
}
}
])
and lastly I have my angular controller which calls the query method from the factory with the id being the id from the url:
.controller('eventCtrl', function($scope, $routeParams, eventFactory) {
var eventId = $routeParams.event_id;
$scope.eventData = eventFactory.query(eventId);
})
The return data seems to be just the entire events.json file rather than just the specific id I want to query for in the parameters. In the params I am trying id but that is obviously not correct. Using this setup how can I return just the data from event_id: 2?
Assuming your production scheme is going to be fetching just a static file that doesn't do anything with arguments passed in, you need to extract the record you need after it's returned from the server.
Basically, you're requesting something like http://yourhost.com/assets/events.json?event_id=3 and if it's just a static file, the server can't do anything with that parameter. In practice, I would think you'd actually be requesting a response from a web service that can handle that, in which case your client-side code would probably work as-is.
In this specific case, however, I would think that you could handle this with an interceptor. Something like this:
.factory('eventFactory', ['$resource',
function($resource) {
return {
query: function(event_id) {
return $resource('/assets/events.json', {}, {
query: { method: 'GET', isArray: false,
interceptor: {response:
function(data){ var d = JSON.parse(data);
return d[event_id];
}
}
}
});
}
}
}
])
I don't have an environment set up to test this at the moment, but I think it should work. I have a couple places in my own code where I do something similar, for other reasons.

AngularJS - Check my implementation of resource factory

Just starting out on AngularJS & js (being a backend developer) and this is the first Javascript MVC framework which I have ever worked on so please go easy...
I have a restful json API which I would like to consume using AngularJS.
In order to implement this, I have created two factories, one singular for when a controller needs to query the factory with an id, and a plural factory for when id is not required.
e.g. below:
Controller to list all products:
app.controller('ProductController', function($scope, ProductsFactory) {
$scope.products = [];
init();
function init()
{
$scope.products = ProductsFactory.query();
}
});
Factories:
app.factory('ProductsFactory', function($resource) {
return $resource('/xxx/xxx/xxx/api/v1/product', {}, {
query: { method: 'GET', isArray: true },
create: { method: 'POST' }
});
});
app.factory('ProductFactory', function($resource) {
return $resource('/xxx/xxx/xxx/api/v1/product/:id', {}, {
show: { method: 'GET' },
update: { method: 'PUT', params: { id: '#id' } },
delete: { method: 'DELETE', params: { id: '#id' } }
});
});
Question 1: Am I implementing the resource factory correctly?
Question 2: Is there a way of just using one factory for Products? e.g. allowing the factory to decide that id is not necessary for query and create, but is required for show, update and delete methods?
Yes, you can use just 1 factory :
app.factory('ProductFactory', function($resource) {
return $resource('/xxx/xxx/xxx/api/v1/product/:id', { id : '#id'}, {
update: { method: 'PUT' },
});
});
You don't need to specify the 'params' object to every requests. Defining it for the $resource is often enough (but if you want to overwrite it of course you can use it).
Notice that you don't need to define the CRUD methods since the $resource already implements them (as stated in the doc : http://docs.angularjs.or/api/ngResource.$resource).
At the moment, you just need to define a custom method update if you want to use "PUT" but a pull request is opened (https://github.com/angular/angular.js/pull/3416) and I hope we can expect to see it implemented soon.

is it possible to include an event in a javascript function?

i was just wondering if getting a jqgrid event from a main javascript and separate it using another javascript in a form of function would work? what im trying to do is like this. i have a code :
...//some code here
serializeGridData: function(postData) {
var jsonParams = {
'SessionID': $('#eSessionID3').val(),
'dataType': 'data',
'recordLimit': postData.rows,
'recordOffset': postData.rows * (postData.page - 1),
'rowDataAsObjects': false,
'queryRowCount': true,
'sort_fields': postData.sidx
};
if (postData.sord == 'desc')
{
...//some code here
}
else
{
...//some code here
}
return 'json=' + jsonParams;
},
loadError: function(xhr, msg, e) {
showMessage('errmsg');
},
...//some code here
i want to get this code and write this in another javascript file and make this as a function, so that my other file could use this one..is it possible?
i created something like this in my other javascrtip file where i planned to put all my functions. here's the code (functions.js):
function serialLoad(){
serializeGridData: function(postData) {
var jsonParams = {
'SessionID': $('#eSessionID3').val(),
'dataType': 'data',
'recordLimit': postData.rows,
'recordOffset': postData.rows * (postData.page - 1),
'rowDataAsObjects': false,
'queryRowCount': true,
'sort_fields': postData.sidx
};
if (postData.sord == 'desc')
{
...//some code here
}
else
{
...//some code here
}
return 'json=' + jsonParams;
},
loadError: function(xhr, msg, e) {
showMessage('errmsg');
}
}
this isn't working and display a message syntax error. i don't know how to correct this. is there anyone who can help me.?
First of all the answer on your derect question. If you define in the functions.js file some global variable, for example, myGlobal:
myGlobal = {};
myGlobal = serializeGridData: function(postData) {
// ... here is the implementation
};
you can use it in another JavaScript file which must be included after the functions.js file:
serializeGridData: myGlobal.serializeGridData
(just use such parameter in the jqGrid definition).
If you want to use the serializeGridData parameter with the value in the most of your jqGrids you can overwrite the default value of serializeGridData in the functions.js file instead:
jQuery.extend(jQuery.jgrid.defaults, {
datatype: 'json',
serializeGridData: function(postData) {
// ... here is the implementation
},
loadError: function(xhr, msg, e) {
showMessage('errmsg');
}
});
In the example I ovewride additionally default datatype: 'xml' jqGrid parameter to datatype: 'json'. It shows that in the way you can set default values of any jqGrid parameter.
What it seems to me you really need is to use prmNames jqGrid parameter to rename some defaulf names of the standard jqGrid parameters. For example with
prmNames: {
rows:"recordLimit",
sort: "sort_fields",
search:null,
nd:null
}
you rename the standard rows parameter to recordLimit, the sidx to sort_fields and remove _search and nd parameters to be send.
Additionally you can use postData having some properties defined as the function (see here for details). For example:
postData: {
SessionID: function() {
return $('#eSessionID3').val();
},
rowDataAsObjects: false,
queryRowCount: true,
dataType: 'data',
recordOffset: function() {
var pd = jQuery("#list2")[0].p.postData;
return pd.recordLimit * (pd.page - 1);
},
json: function() {
var pd = jQuery("#list2")[0].p.postData;
return {
SessionID: $('#eSessionID3').val(),
dataType: 'data',
recordOffset: pd.recordLimit * (pd.page - 1),
rowDataAsObjects: false,
queryRowCount: true,
sort_fields: pd.sort_fields
};
}
}
I used here both json parameter which you currently use and add parameters like SessionID, queryRowCount and so on directly in the list of parameters which will be send. Of course it is enough to send only one way (either json or the rest) to send the aditional information which you need.
The second example is incorrect, as you are declaring a javascript object as the body of a function, what you could do is:
function serialLoad() {
// Return an object with the required members
return {
serializeGridData: function(postData) { ... },
loadError: function(xhr, msg, e) { ... }
};
}
You are mixing function declaration and object literal notation. This syntax: property: value is used when creating an object with object literal notation:
var obj = {
prop: val,
prop2: val
};
serializeGridData and loadError are properties of some object and you cannot define those by just putting them into a function.
One way would be to create two functions, one for serializeGridData and one for loadError, e.g.
function serialLoad(postData){
var jsonParams = {
//...
};
if (postData.sord == 'desc') {
//... some code here
}
else {
//... some code here
}
return 'json=' + jsonParams;
}
function onError(xhr, msg, e) {
showMessage('errmsg');
}
Then you can assign them in your other file to the object:
// ... some code here
serializeGridData: serialLoad,
loadError: onError,
//... some code here
Another way is to pass the object in question to the function and assign the properties there:
function attachLoadHandler(obj) {
obj.serializeGridData = function(postData) {
//...
};
obj.loadError = function(xhr, msg, e) {
//...
};
}
Then you have to pass the object you created to that function:
attachLoadHandler(obj);
But I think the first approach is easier to understand.

Categories

Resources