Want to use angularjs resource object with action method - angularjs

I want to make a search query to my server with angularjs resource object and i have written such an resource object;
app.factory('EcriDeviceListService', function ($resource) {
var Url = "http://localhost:60766/api/EcriDeviceLists/:id/:queryText";
return $resource(Url, { id: '#Id' },{ update: { method: 'PUT' },'search': { method:'GET', {queryText:''}})
});
with this code i want to make a search query like this;
EcriDeviceListService.search({queryText:'abc'})
http://localhost:60766/api/EcriDeviceLists/queryText=abc"
how should i configure my resource object.
Thanks.

You should configure $resource object like this:
$resource('http://localhost:60766/api/EcriDeviceLists/:id/:queryText', {
id: '#Id',
queryText: ''
}, {
update: {
method: 'PUT'
},
search: {
method: 'GET'
}
});

Related

AngularJS - How to Send Common URL Parameters on All Request?

I want to send the same url param on all requests either it's get or post request, like this:
?region=us&toolName=abc
Is it possible by using AngularJS interceptor? Or is there other better way?
Thanks for your help.
Using an httpInterceptor would be best then you can check if other params already exist and extend them...or only use the ones shown
The AngularJS $http method lets you specify your HTTP request verb as well as such parameters via the config object which can contain a params object, which can be something like { region: "us", toolName: "abc" } which in turn becomes a query string. Example use:
$http({ url: "test.aspx", method: "GET", params: { region: "us", toolName: "abc" } }).then(
function(response){
alert("success!");
}, function(response){
alert("failure.");
}
Create a service to set default params request:
'use strict';
var ParamsService = function() {
return {
set: function (params) {
var defaultParams = {
region: 'us',
toolName: 'abc'
};
// Use any function to extend objects (currently, I'm using lodash)
return _.extend(defaultParams, params);
}
};
};
ParamsService.$inject = [
];
Request:
$http({
url: 'url.json',
method: 'GET',
params: ParamsService.set({otherProperty: otherValue})
})
.then(
function (data) {
},
function (error) {
}
);
It not good solution, but can help your case :)
$httpProvider.defaults.headers.common['key'] = 'value'

AngularJS NgResource API call

So I'm currently working with $ngResouce. My api: api/Content/resource/user.post.failed returns the following:
{
"user.post.failed": "Thing.."
}
app.factory('testResource', function ($resource) {
return $resource(apiurl + '/Content/resource/:resourcename', {}, {
show: { method: 'GET', isArray: false, params: {resourcename: '#resourcename'} },
update: { method: 'PUT', params: {id: '#id'} },
delete: { method: 'DELETE', params: {id: '#id'} }
})
});
This is what I call in my controller
$scope.test = testResource.get({resourcename: 'test'});
The question is actually really simple; how do I get just the 'content part' so test. I'm now getting the whole JSON part back.
So the scope test is now: {"user.post.failed":"Thing.."}
And I want the scope to be just Thing.
Probably really simple, but I couldn't find the answer.
Use the $promise property of the object to see errors:
$scope.test = testResource.get({resourcename: 'test'});
$scope.test.$promise.catch(function onReject(response) {
console.log('ERROR: ',response.status);
console.log(response);
});
So the scope test is now: {"user.post.failed":"Thing.."} And I want the scope to be just Thing.
console.log($scope.test["use.post.failed"]);
Use the property accessor syntax.
For more info see MDN JavaScript Reference -- Property Accessors
HTML
{{ test["use.post.failed"] }}
testResource.get({resourcename: 'test'}, function(data) {
$scope.test = data['user.post.failed'];
})

"Suggest slug name" API call in ngResource in AngularJS/Express app

I want the user to be able to set the slug name (URL) for a document in my app, but also I need some control so users don't override each other. It needs to be a separate call (not integrated with create/update) so the user can get visual feedback on their own slug name suggestions.
Therefore I've created a suggestSlug API call that takes an optional slug parameter as seed for the final slug name.
This is what my Express routes looks like:
app.get('/api/projects/suggestSlug/:slug', projects.suggestSlug);
app.get('/api/projects/suggestSlug', projects.suggestSlug);
app.get('/api/projects', projects.list);
app.get('/api/projects/:id', projects.show);
Now, I want to extend ngResource on the client side (AngularJS) to make use of this API:
angular.module('myapp.common').factory("projectModel", function ($resource) {
return $resource(
"/api/projects/:id",
{ id: "#id" },
{
update: { method: "PUT", params: { id: '#_id' } },
del: { method: "DELETE", params: { id: '#_id' } }
}
);
});
How do I extend the ngResource client to use my new API?
This was my solution: adding a separate $http-based method to my projectModel:
angular.module('myapp.common').factory("projectModel", function ($resource, $http) {
var projectModel = $resource(
"/api/projects/:id",
{ id: "#id" },
{
update: { method: "PUT", params: { id: '#_id' } },
del: { method: "DELETE", params: { id: '#_id' } }
}
);
projectModel.suggestSlug = function (slugSuggestion, callback) {
$http.get(
'/api/projects/suggestSlug/' + slugSuggestion
).success(callback).error(function(error) {
console.log('suggestSlug error:', error);
});
};
return projectModel;
});

Kendo-UI datastore leveraging Angular $resource

I am attempting to implement a abstraction over a RESTful back-end for my persistence layer and have ran into something I find a little confusing. I am using the angular framework and more specifically the ngResource module to get access to the $resource service. I can execute my queries and work against the back-end without issue. My problem comes when integrating back into my kendo-ui datasource, the datasource never recognizes when the query has returned. From my understanding the $resource will immediately return a empty collection (array) for possible assignment and then populate that array with the results of the query when it finishes. Kendo-ui's DataSource should watch this variable and upon update reflect this back to anyone leveraging the datasource. I have successfully implemented this using a slightly different model (passing a object literal that I update myself as required) and the DataSource has no problem recognizing the updates. Any insight would be helpful!
app.provider('remotePersistence', function () {
this.$get = function ($resource) {
var definitions = {
widgets: $resource('http://127.0.0.1:3000\:3000/widget.json',{},{
archive: { method: 'POST', params: { archive: true }},
active: { method: 'POST', params: { active: true }}
})
};
var datastore = {}
var namespaces = ['widgets'];
namespaces.forEach(function (namespace) {
datastore[namespace] = {
endpoint: definitions[namespace],
cache: definitions[namespace].query()
};
});
return datastore;
};
});
app.controller(
"WidgetsSearchController",
function ($scope, remotePersistence){
$scope.widgets = undefined;
$scope.visibleWidgets = new kendo.data.DataSource({
// data: remotePersistence.widgets.cache,
transport: {
read: function (options) {
options.success(remotePersistence.widgets.cache);
}
}
});
});
//This works but is not desirable style
//$scope.widgets = remotePersistence.widgets.query(function(){ $scope.visibleWidgets.data($scope.widgets) });
The data source needs to be notified that data has been received. Perhaps the ngResource module will trigger some callback or event when it finishes loading data. Then you can use the data() method of the Kendo DataSource to populate it with data items. All Kendo UI widgets bound to that data source will receive a notification when you use the data method.
For anyone following behind here is my current implementation that works nicely. I am still a bit unhappy with the manipulation I must do for the sort to be passed but it works along with paging.
app.controller(
"WidgetSearchController",
function ($scope, remotePersistence){
$scope.visibleWidgets = new kendo.data.DataSource({
widget: {
read: function (options) {
if(options.data.sort){
options.data.order = _.map(options.data.sort, function (sortItem) {
return sortItem.field + " " + sortItem.dir
}).join(", ");
}
remotePersistence.widgets.endpoint.query(options.data, function(response){
console.log(response);
options.success(response);
});
}
},
schema: {
data: "widgets",
total: "total"
},
pageSize: 20,
serverSorting: true,
serverPaging: true
// serverFiltering: true
});
});
app.provider(
'remotePersistence',
function () {
this.$get = function ($resource) {
var definitions = {
widgets: $resource('http://127.0.0.1:3000\:3000/widgets/:id',{ id: '#id' },{
archive: { method: 'PUT', params: { archive: true }},
update: { method: 'PUT' },
active: { method: 'PUT', params: { active: true }},
query: { method: 'GET', isArray: false},
})
};
var datastore = {}
var namespaces = ['widgets'];
namespaces.forEach(function (namespace) {
datastore[namespace] = {
endpoint: definitions[namespace],
cache: definitions[namespace].query()
};
});
return datastore;
};
});

Angularjs resource builds wrong resource url

Resource:
angular.module('TicketService', ['ngResource'])
.factory('Ticket', ['$resource', function($resource){
var Ticket = $resource('/api/tickets/:id1/:action/:id2',
{
id1:'#id'
},
{
list: {
method: 'GET'
},
listByOwner: {
method: 'GET',
params: {
action:'owner',
id1:"#id"
}
}
update: {
method: 'PUT',
params:{}
}
});
return ticket;
}]);
Query:
$scope.userTickets = Ticket.listByOwner({
id : $rootScope.user.id
}, function(){
//success
}, function(response){});
Result:
Angularjs builds a wrong url, /api/tickets but it should be /api/tickets/2/owner. Any ideas why?
The # indicates that angular should look for the attribute on the data object, which is the second parameter (optional) in the Ticket service methods. In the first parameter you specify the request parameters. There are two ways you can fix this:
Add an empty object as the first parameter
$scope.userTickets = Ticket.listByOwner({},{
id : $rootScope.user.id
}, function(){
//success
}, function(response){});
Or rename the request parameter object key (from id to id1):
$scope.userTickets = Ticket.listByOwner({
id1 : $rootScope.user.id
}, function(){
//success
}, function(response){});

Resources