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;
});
Related
I am using $resource service for my crud operations now i want to get data on a condition like get appointments whose starting date is today. I am fetching all data by
vm.appointments = AppointmentsService.query();
and my service code is
(function () {
'use strict';
angular
.module('appointments')
.factory('AppointmentsService', AppointmentsService);
AppointmentsService.$inject = ['$resource'];
function AppointmentsService($resource) {
return $resource('api/appointments/:appointmentId', {
appointmentId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
})();
Now can i give condition in this code blockAppointmentsService.query({condition}); or change my service in node rest API.
If yes, then what will be my AppointmentsService.query call
For your different url path, you can create new method like below or you can pass startDate as a query string
Controller :
For Path Param
vm.appointments = AppointmentsService.searchByDate({date:'03/30/2016'});
For Query Param
vm.appointments = AppointmentsService.searchByDate({StartDate:'03/01/2016',EndDate:'03/30/2016'});
Service:
function AppointmentsService($resource) {
return $resource('api/appointments/:appointmentId', {
appointmentId: '#_id'
}, {
update: {
method: 'PUT'
},
// For Path Param
searchByDate :{
method : 'GET',
url : 'your url/:date'
},
// For Query Param
searchByDate :{
method : 'GET',
url : 'your url/:startDate/:endDate' ,
params : { startDate : '#StartDate', endDate : '#EndDate' }
}
});
}
Update your service code...
(function () {
'use strict';
angular
.module('appointments')
.factory('AppointmentsService', AppointmentsService);
AppointmentsService.$inject = ['$resource'];
function AppointmentsService($resource) {
var service = {
get: $resource('api/appointments/:appointmentId',{
appointmentId: '#_id'
},{
method:'GET'
}),
update: $resource('api/appointments/:appointmentId',{
appointmentId: '#_id'
},{
method:'PUT'
}),
query:$resource('api/appointments',{
method:'GET',
isArray:true
})
queryByStartDate:$resource('api/appointments/:startDate',{
startDate: '#_startDate'
},{
method:'GET',
isArray:true
})
}
return service;
}
})();
And call queryByStartDate inside controller
var startDate = new Date(); //you can use $filter to format date
$scope.appointments = AppointmentsService.queryByStartDate({startDate:startDate});
I have multiple factories in my angular service located in different js file. And there is common base of all the queries:
1) Authorization: Bearer token (header) (required after login)
2) AccessDateTime, UserIPAddress (required before login)
3) AccessDateTime, UserIPAddress, UserID (required after login)
Now, I find that it is very tedious to repeat this on each of the resource. How could i make a base for this? I thought that this is something very common but i could not found any documentation on this. Something like jquery.AjaxSetup().
Default Code
angular.module('app.test').factory('Test', ['$resource',
function($resource) {
return {
resource1: $resource(
url: 'test1/:testId/:AccessDateTime/:UserIPAddress',
headers: { Authorization: Bearer token},
params: { testId: '#_id', AccessDateTime:'#AccessDateTime', UserIPAddress: '#UserIPAddress' }
}),
resource2: return $resource(
url: 'test2/:testId/:AccessDateTime',
params: { testId: '#_id', AccessDateTime:'#AccessDateTime' }
});
}
}
]);
Code after base resource implemented(Illustration only)
angular.module('app.base').factory('FactoryBase'), ['resource',
function($resource) {}
if (resource need authorization) {
auto append header, AccessDateTime, UserIPAddress
} else if (resource do not need authorization) {
auto append AccessDateTime
}
// depending on attribute set with authorize: true/false
}
]);
angular.module('app.test').factory('Test', ['$resource',
function($resource) {
require('FactoryBase'),
return {
resource1: $resource(
url: 'test1/:testId',
authorize: true
}),
resource2: $resource(
url: 'test2/:testId',
authorize: false
}),
}
]);
Put modifier functions in your factory:
angular.module('app.test').factory('Test', ['$resource',
function($resource) {
var defaultConfig1 = {
url: 'test1/:testId/:AccessDateTime/:UserIPAddress',
headers: { Authorization: Bearer token},
params: { testId: '#_id',
AccessDateTime:'#AccessDateTime',
UserIPAddress: '#UserIPAddress'
}
};
var defaultConfig2 = {
url: 'test2/:testId/:AccessDateTime',
params: { testId: '#_id',
AccessDateTime:'#AccessDateTime'
}
};
function mod1(arg) {
var obj = defaultConfig1;
//modify config
return obj;
};
function mod2(arg) {
//modify and return defaultConfig
};
return {
resource1: $resource(defaultConfig1),
resource2: $resource(defaultConfig2).
modified1: function (arg) {
return $resource(mod1(arg));
},
modified2: function (arg) {
return $resource(mod2(arg));
}
}
}
]);
You have the full power of JavaScript to modify the configuration objects as you please before returning them.
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'
}
});
Hello I need to find/update users from a mongodb collections via angular.
And I need to find them by _id and by username, so I created a service like this:
// Users service used for communicating with the users REST endpoint
angular.module('users').factory('Users', ['$resource',
function($resource) {
return $resource('users/:id', {}, {
update: {
method: 'PUT'
}
});
}
]);
And on Express I have the relative API route:
app.route('/users/:userId').put(users.update);
Now, suppose I have another express route like this to check username availability:
app.route('/users/:username').get(users.check);
How can I integrate this last one in the same angular service?
UPDATE:
Solved with this, is it right?
angular.module('users').factory('Users', ['$resource',
function($resource) {
return {
byId: $resource('users/:id', {}, {
update: {
method: 'PUT'
}
}),
byUsername: $resource('users/:username', {}, {
})
};
}
]);
Do you want to do something like this?
Angular service:
angular.module('users').factory('Users', function($resource) {
var resource = $resource('users/:byAttr/:id', {}, {
update: {
method: 'PUT',
isArray: false,
cache: false
}
});
return {
updateById: function (id) {
resource.update({id: id, byAttr: 'id'});
},
updateByName: function (username) {
resource.update({username: username, byAttr: 'username'});
},
}
});
Routes:
app.route('/users/id/:userId').put(users.update);
app.route('/users/user/:username').get(users.check);
If I have a url like this "http : // x.x.x.x:port"
app.factory("myservice", function($resource){
var res = function(){
return $resource("http://x.x.x.x:port/profile/:userID", {
{
getUserInfo: {
method: "GET",
params: {userID : "userNumber"},
headers:{
"Accept": "application/json",
"Content-Type": "application/json",
sessionID : "sesionIDNumber"
}
}
},
});
}
console.log( res.get("firstName") );//error GET http://myurl/myport/profile?0=l&1=a&2=s&3=t&4=n&5=a&6=m&7=e®=%7B%2…2Fjson%22,%22sessionId%22:%22b1bfa646-215e-4223-be8c-b53d578ba379%22%7D%7D 404 (Not Found)
});
If I want to get the user's infoes, what do I have to do?
You can use like this
app.factory("myservice", function($resource)
{
return $resource('http://x.x.x.x:port/profile/:userID/:sessionID', {
userID : '#userID'
sessionID: "#sessionID"
});
});
A best example is shown below
app.factory('Books', ['$resource', function($resource) {
return $resource( '/book/:bookId',
{ bookId: '#bookId' }, {
loan: {
method: 'PUT',
params: { bookId: '#bookId' },
isArray: false
}
/* , method2: { ... } */
} );
}]);
At this point it is really simple to send requests to the web service, that we build in the previous post.Everywhere it is possible to inject the Books service it is possible to write:
postData = {
"id": 42,
"title": "The Hitchhiker's Guide to the Galaxy",
"authors": ["Douglas Adams"]
}
Books.save({}, postData);
// It sends a POST request to /book.
// postData are the additional post data
Books.get({bookId: 42});
// Get data about the book with id = 42
Books.query();
// It is still a GET request, but it points to /book,
// so it is used to get the data about all the books
Books.loan({bookId: 42});
// It is a custom action.
// Update the data of the book with id = 42
Books.delete({bookId: 42});
// Delete data about the book with id = 42