How to use Angular Query resource - angularjs

I'm using MEAN.JS 0.4 and I need some help with Angular Resource.
My problem is this:
I want to make this API and be able to filter data server side, but I dont know how to use this Query method.
I want to do something like this:
Products.query({
stock: 0
}, function(result){
console.log(result)
});
This is my actual Angular service:
//Discounts service used for communicating with the discounts REST endpoints
angular.module('discounts').factory('Discounts', ['$resource',
function ($resource) {
return $resource('api/discounts/:discountId', {
discountId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
]);

Discounts.query({stock: 0}).$promise
.then(function(data) {
products = data; })
or
products = Discount.query({stock: 0}, function() {
//do something whith products
});

Related

How can I save JSON data from an API service to cache?

I call the API service from the backend side. I want to save the JSON return data to the cache. What should I do? Is my format wrong?
The snippet code here:
// var localData = [];
var service = {
search: function(requestId) {
return $http.get('/api/mace/getRequest', {
params: {
id: requestId
},
cache:true
});
},
return service
I can't see that there's something wrong with your code. You did correctly set the cache variable to true in the http-call as described in the documentation from AngularJS.
$http.get(url, {
cache: true
}
You should get your JSON by calling your service function and waiting for the promise:
yourService.search(yourRequestId).then(function(response) {
console.log('result', response.data);
});

Unable to use $update, $remove and $save in ngresource

I am using ngresource as follows but unfortunately I am unable to access the $update, $remove and $save methods in this way. What am I doing wrong?
angular.module('myApp.services').factory('Entry', function($resource) {
return {
method1: $resource('/api/entries/:id', { id: '#_id' }, {
update: {
method: 'PUT' // this method issues a PUT request
}
}),
method2: $resource('/api/entries2', {}, {
})
});
// not working: Entries is not a function at Scope.$scope.save
var entry = new Entries({});
entry.method1.$update();
entry.method1.$save();
entry.method1.$delete();
On the other hand, this works:
angular.module('myApp.services').factory('Entry', function($resource) {
return $resource('/api/entries/:id', { id: '#_id' }, {
update: {
method: 'PUT' // this method issues a PUT request
}
});
});
var entry = new Entries({});
entry.$update();
entry.$save();
entry.$delete();
So your second example doing $resource('http://example.com/resource.json') is the correct usage of that construction, while the first one is not.
After executing var entry = new Entries({}); you get entry as factory instance in your controller, which has available actions that you've defined for it.
UPD
You can have multiple resources in the service - https://stackoverflow.com/a/17163459/405623. In your example you've just missed the ['ngResource'] DI in your module.

How to structure urls in angularjs

Currently my url structure in angularjs is as follows. When I load the page I use
Orders.query
and when I try to update using
order.update()
But once I put conditions like search and then fetch orders, update them using
order.update()
it tries to call PUT on conditioned/orders as the new orders are fetched using the Fetch factory method. Is there any better way to merge the urls to make it more meaningful. Is there any standard followed in this sort of cases?
angular.module('orders').factory('Orders', ['$resource',
function($resource) {
return $resource('orders/:orderId', {
orderId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
]).factory('Search', ['$resource',
function($resource) {
return $resource('search/orders/', {},{
conditioned: {
method:'GET', params:{}, isArray:true
}
});
}
])
Routes on server side(Expressjs) are
app.route('/orders')
.get(orders.list)
.post(users.requiresLogin, orders.create);
app.route('/orders/:orderId')
.get(orders.read)
.put(users.requiresLogin, orders.update)
.delete(users.requiresLogin, orders.delete);
app.route('/search/orders')
.get(orders.search);

Getting a single result with angularjs factory in MEAN stack

I'm trying to grab a single result from my expressjs api from within my AngularJS factory.
The factory looks like this and grabs all posts from my api(written in expressjs and getting data from mongodb), which is working fine:
angular.module('bonsaiService', ['ngResource']).
factory('bonsaiService', function($q,$resource) {
var bonsaiResource = $resource('http://localhost:8888/api/bonsais/:bonsaiId',{},{
get:{
method: 'GET',
params:{bonsaiId:''},
isArray: true
}
});
return {
get:function(){
var q = $q.defer();
bonsaiResource.get({
},
function(resp){
q.resolve(resp);
},function(httpResponse){
q.reject(httpResponse);
});
return q.promise;
}
//find by id
};
});
What i've tried so far is adding :bonsaiId after the $resource url and adding params for that id like this: params:{bonsaiId: ''}.
The server part (expressJS) look like this:
router.route('/bonsais/:bonsaiId')
.get(function(req,res){
Bonsai.findOne(req.params.bonsaiId,function(err,bonsai){
if(err)
res.send(err);
res.json(bonsai)
})
})
When I call a local url (with and existing _id from mongodb) it works fine and returns my data in json :
http://localhost:8888/api/bonsais/536be2e2ae54668818000001
Now in the controller im trying to get this data in my scope, which is not working.
bonsaiService.get({bonsaiId:$routeParams.bonsaiId}).then(
function(data){
$scope.trees = data;
console.log(data);
});
How do I make this work?
You could use a more simple approach here.
The query method for $resource already defines a GET on an array, which is QUERY.
Why not write your service this way :
.factory('bonsaiService', ['$resource',
function($resource) {
return $resource('http://localhost:8888/api/bonsais/:bonsaiId', {
bonsaiId: '#bonsaiId'
});
}
])
And in your controller, it would work like this :
bonsaiService.query({
bonsaiId: $routeParams.bonsaiId
}, function success() {
//Your code
}, function err() {
//Your code
});
Don't forget to inject the service in the controller or the app file, if it's not done already.

AngularJS: POSTing something new with $resource

I'm having trouble using $resource to POST something new... It works great for updates & queries, but when I try and create a new 'article', its getting a little confusing.
Basically my POST should be sent to "/articles/". The ID of the article is set through the form on the front end, however when I submit the POST it is sent to "/articles/ARTICLE_ID"(ARTICLE_ID being replaced with whatever I set on the form).
Here is my article service:
angular.module('testapp.articles')
.factory("Articles", ['$resource', function($resource) {
return $resource('articles/:articleId', {
articleId: '#articleId'
}, {
update: {
method: 'PUT'
}
});
}]);
This is my controller:
$scope.create = function() {
var article = new Articles({
articleId: this.articleId
});
article.$save(function(response){
console.log(response);
});
};
Any help is appreciated, thanks!
It goes off to /articles/ARTICLE_ID because that is what you specified while creating the Article. You do not need to supply article_id as a parameter.
$scope.create = function() {
var article = new Articles();
article.articleId = this.articleId
article.$save();
...
};
With the newer versions of AngularJS, articleId will be picked up anyway. Your service could be simplified as follows:
angular.module('testapp.articles')
.factory("Articles", ['$resource', function($resource) {
return $resource('articles/:articleId', null,
{
'update': { method: 'PUT' }
});
}]);
AngularJS $resource

Resources