I'm trying to add a layer of abstraction between the angular $resource received and my controller. I have to perform a few operations like filtering, so I setup a service to perform these in-between functions.
I was able to set up this first resource call with no problems:
/**
* Get Grid
*
* retrieves grid resource and serializes the grid, rows, columns and widgets themselves
*/
this.getGrid = function() {
var gridResource = new GridResource();
var response = gridResource.$query();
var accGrid = new Grid;
response.then(function(response) {
angular.forEach(response.grid, function(row) {
var accRow = new Row;
angular.forEach(row.columns, function(column) {
//Setting up new Column
var accColumn = new Column();
accColumn.setId(column.id);
//Setting up new Widget(s)
var accWidget = new Widget;
accWidget.setId(column.widget.id);
accWidget.setName(column.widget.name);
accWidget.setType(column.widget.type);
accWidget.setChildren(column.widget.children);
accWidget.setVars(column.widget.vars);
accColumn.addWidget(accWidget);
accRow.addColumn(accColumn);
});
accGrid.addRow(accRow);
});
});
return accGrid;
};
This returns the Grid object with all of the populated parts.
However when I try to do perform the same method on a different endpoint, Angular complains:
http://puu.sh/eUSbx/3c15a8b13a.png
I only got to this point in the method:
/**
* Get all Widgets
*
* Retrieves all widgets belonging to the route, regardless if they are in the canvas or not
*/
this.getWidgets = function() {
var widgets = new Array();
var widgetResource = new WidgetResource();
var response = widgetResource.$query();
response.then(function(response) {
console.log(response);
});
return widgets;
};
If you're wondering about the $resource itself:
designService.factory('GridResource', ['$resource',
function($resource){
return $resource('view/canvas', {},
{
query: { method:'GET' },
save: { method:'POST' }
});
}]);
designService.factory('WidgetResource', ['$resource',
function($resource) {
return $resource('view/widget', {},
{
query: { method:'GET', isArray: true }
});
}]);
I'm a PHP guy moving into the wonderful weird world of frontend JS and could really use a pointer :sweaty-smile: thanks!
** Update ** I've learned how Angular uses then to catch error responses too, so I updated my query:
widgetResource.$query().then(
function(response) {
console.log(response);
},
function(error) {
console.log(error);
}
);
Which produced this error:
http://puu.sh/eUYYx/998c73600a.png
Your code seems good, Look around your dependency injection in your controller. You may have missed one or misspelled ?
** Got the answer **
Angular is so damn picky! The problem was I was trying to create a new resource object from one that was already given. Directly assigning the response to to the result of WidgetResource.query() was sufficient. This maybe due to the fact I have the WidgetResource.query() have the isArray property to true.
/**
* Get all Widgets
*
* Retrieves all widgets belonging to the route, regardless if they are in the canvas or not
*/
this.getWidgets = function() {
var widgets = new Array();
//var widgetResource = new WidgetResource();
var response = WidgetResource.query();
response.$promise.then(
function(response) {
console.log(response);
},
function(error) {
console.log(error);
}
);
Related
I am using a Restangular library in my angularjs application.I want to retrieve all registered user's information from rest api.Whenever I make Restangular GET request to do so it retrieves only 100 records while I have around 250+ users for my website.I've tried using
Restangular.all('url').getList({limit:200,offset:0})
.then(function (success) {
//some code
});
This was the wayout mentioned here but it isn't working for me.
Found solution after some time
RestFullResponse.all('url').getList().then(function (success) {
var headers = success.headers();
var currentpage = headers['x-pager-current-page'];
var lastpage = headers['x-pager-last-page'];
for(currentpage; currentpage<=lastpage; currentpage++) {
var param = {
"page_entries": 100,
"page":currentpage,
"offset": (currentpage-1)*this.page_entries
};
RestFullResponse.all('url').getList(param).then(function (success) {
personList = personList.concat(success['data']);
});
}
});
I am trying to get the metadata before I perform any queries on the page, because each query is trying to get the metadata for a total of 5 times and the page is very slow. I am hoping this helps.
//version info:
var breeze = {
version: "1.5.4",
metadataVersion: "1.0.5"
};
Howevever I am getting this error:
manager.fetchMetadata(...).then(...).fail is not a function
Here is the code sample:
var manager = emProvider.createManager();
function getMetaData()
{
var deferred = $q.defer();
manager.fetchMetadata()
.then(function (data, status) {
deferred.resolve(data);
console.log('manager.fetchMetadata() success');
})
.fail(function (data, status) {
deferred.reject(data);
console.log('manager.fetchMetadata() reject');
});
return deferred.promise;
}
THis is what the createManager function looks like from the injected 'emProvider' service.
var masterManager = new breeze.EntityManager(serviceRoot + 'odata/');
// private function to create a new manager
function createManager() {
var manager = masterManager.createEmptyCopy(); // same configuration; no entities in cache.
// ... copy in some entities (e.g.,picklists) from masterManager
return manager;
}
try the following... surround all of your code blocks with anonymous self-invoking functions except for the master manager creation, comment out the getMetaData function, be sure to pick up the right adapter for your service... breeze odata configuration , make sure Q is on your js bundle at the top of your page.
breeze.config.initializeAdapterInstance("dataService", "odata");
var masterManager = new breeze.EntityManager(serviceRoot + 'odata/');
(function () {
var op = breeze.FilterQueryOp;
var query = null;
query = new breeze.EntityQuery()...
...all of your other breeze code...
masterManager.executeQuery(query).then(function (data) {...
})();
If you are using $q from AngularJS, you should use .catch instead of .fail. AngularJS uses .catch for errors in promises.
Problem description
Im using the angular resource to get data from my server. I've extended it a bit to make sure all of my resources have security headers.
Problem is that on the second get request and on, my get requests are sent with limit=0, and only the first get request is sent correctly (with limit=12).
Code part
This is my base resource factory (for making sure all resource contain the keys and everything):
app.factory('SecuredFactory', function($resource){
var DEFAULT_ACTIONS = {
'get': {method:'GET'},
'query': {method:'GET', isArray:true},
};
var DEFAULT_PARAMS = {
'limit': 12,
'format': 'json'
};
for(var key in DEFAULT_ACTIONS){
DEFAULT_ACTIONS[key]['headers'] = <headers object>;
}
var securedResource = function(url, paramDefaults, actions){
for (var attrname in actions) {
DEFAULT_ACTIONS[attrname] = actions[attrname];
}
for (var attrname in paramDefaults) {
DEFAULT_PARAMS[attrname] = paramDefaults[attrname];
}
var defaultResource = $resource(url, DEFAULT_PARAMS, DEFAULT_ACTIONS);
return defaultResource;
};
return securedResource;
});
And this is an example of how I creat a specific factory out of the secured one:
app.factory('QuestionFactory', function(SecuredFactory, Constants){
var url = Constants.SERVER_URL + 'question/';
var Task = SecuredFactory(url);
return Task;
});
And this is finally how I use it, for example:
// filtering example (not important for this matter):
var filtering = {author: "Daniel"};
var contents = [];
var resource = QuestionFactory;
resource.get(filtering, function (res) {
// success fetching
$scope.contents = $scope.contents.concat(res['objects']);
}
// failed fetching
, function (err) {
}
);
The requests
first request:
question?format=json&limit=12&offset=0
second request and on:
question?format=json&limit=0&offset=0
My problem was that the DEFAULT_PARAMS variable was declared as global. I didn't realize that invoking the secured factory with {limit: 0} will override the global, therefore changing the limit to 0 for ALL of my resources.
Changing the securedFactory to a service and moving the "globals" into the returned function solved it. Had to add new ofcourse before every securedService call.
Should be a fairly easy one here for anyone who knows Angular. I am trying to update the data that is displayed after I make a PUT request to update the object. Here is some code:
Post service (services/post.js)
'use strict';
angular.module('hackaboxApp')
.factory('Post', function($resource) {
return $resource('/api/posts/:id', {id : '#id'}, {
'update': { method: 'PUT' }
})
});
Server side controller function that gets executed when trying to update data (lib/controllers/api.js)
exports.editsave = function(req, res, next) {
var posty = req.body;
console.log(posty._id.toString() + " this is posty");
function callback (err, numAffected) {
console.log(err + " " + numAffected);
if(!err) {
res.send(200);
//res.redirect('/forum');
}
}
Post.update(posty, { id: posty._id.toString() }, callback);
};
This is the console output for the above code:
53c54a0d4960ddc11495d7d7 this is posty
null 0
So as you can see, it isn't affecting any of the MongoDB documents, but it also isn't producing errors.
This is what happens on the client (Angular) side when a post is updated:
$scope.saveedit = function() {
console.log($scope.post._id + " post id");
// Now call update passing in the ID first then the object you are updating
Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};
After the redirect, $location.path('/forum'), none of the data is displayed as being updated...when I look in the database...nothing has changed either...it is like I am missing the step to save the changes...but I thought that update (a PUT request) would do that for me.
I use ng-init="loadposts()" when the /forum route is loaded:
$scope.loadposts = function() {
$http.get('/api/posts').success(function (data) {$scope.posts = data});
};
Shouldn't all the new data be loaded after this? Any help would be appreciated. Thanks!
Your server side output indicate that the update query doesn't match any document in the database.
I'm guessing that you are using Mongoose in NodeJS server side code to connect to mongodb.
If that the case, your update statement seems incorrect.
Instead of { id: .. } it should be { _id: .. }
Also the conditions object and updated object are swapped.
The statement should be like this:
Post.update({ _id: posty._id.toString() }, posty, callback);
If you are not using Mongoose, please eloborate more on which library you are using or better than that, show the code where the Post variable is defined in your server side code.
Ok I got it.
the problem is that you are not using the Angular resource api correct.
This code need to be changed:
$scope.saveedit = function() {
console.log($scope.post._id + " post id");
Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};
Into:
// Update existing Post
$scope.saveedit = function() {
var editedpost = new Post($scope.post); //New post object
editedpost.$update(function() {
$location.path('/forum');
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
And as for the server code (taken from my own working module):
exports.update = function (req, res) {
var post == req.post;
post = _.extend(post, req.body);
post.save(function (err) {
if (err) {
return res.send(400, {
message: getErrorMessage(err)
});
} else {
res.jsonp(post);
}
});
};
I am having some trouble chaining promises in Angular. What I want to do is fetch my project object from the API, then check if the project owner has any containers, if they do, trigger the another GET to retrieve the container. In the end the container assigned to scope should either be null or the object retrieved from the API.
Right now, this example below resolves immediately to the second then function, and I get the error, TypeError: Cannot read property 'owner' of undefined. What am I doing wrong?
$http.get('/api/projects/' + id).then(function (data) {
$scope.project = data.project;
return data.project;
}).then(function (project) {
var containers = project.owner.containers;
if (containers.length) {
return $http.get('/api/containers/' + containers[0]);
} else {
return null
}
}).then(function (container) {
$scope.container = container;
});
Ah, turns out the data from passed into then is inside a field, so I needed to do
$scope.project = data.data.project;
return data.data.project;
Your example code works, but what if the $http call fails because of a 404? Or you want to later want to add some extra business logic?
In general you want to handle 'negative' cases using a rejecting promise, to have more control over the chaining flow.
$http.get('/api/projects/' + id).then(function (data) {
$scope.project = data.data.project;
return data.data.project;
}).then(function (project) {
var containers = project.owner.containers;
if (containers.length) {
return $q.reject('containers empty');
}
return $http.get('/api/containers/' + containers[0]);
}).then(function (container) {
$scope.container = container;
}).except(function (response) {
console.log(response); // 'containers empty' or $http response object
$scope.container = null;
});