Highly strange error in Angular application - angularjs

I have a SQL Server database and an Asp.net web api for my web service.
I have below UI for adding a category
I have below UI for adding a expense in that category
After I login into the application.
Category:
I am creating a category which is getting created and in the database there is a record. Refreshing the page it displays the category. After logging out and logging in again the category is not displayed here.
Expense :
When I create a new expense, it is not displayed at all. But the created category is taken into the drop down but not displayed as in the screenshot above.
Code as below
Inserting my expense
$scope.insertExpense = function () {
var ExpenseObj = {
"AmountSpent": $scope.amountspent,
"DateofExpense": $scope.datevalue,
"UserID": $rootScope.id,
"CategoryID": $scope.selectedcategory.Id
};
appResources.expenseResource.save(ExpenseObj, function () {
alert("Expense Added");
});
}
I retrieve my category using
appResources.categoryResource.query(function (data) {
$scope.Categories = data;
console.log(data);
});
I retrieve my category using
appResources.expenseResource.query(function (data) {
$scope.Expenses = data;
console.log(data);
});
AppResources has only the webapi calling mechanism as
expenseManager.factory('appResources', function ($resource) {
var baseURL = "http://localhost:8080"
var registerResource = $resource(baseURL+'/api/Register/:id');
var categoryResource = $resource(baseURL + '/api/Category/:id');
var expenseResource = $resource(baseURL + '/api/Expense/:id');
return {
registerResource: registerResource,
categoryResource: categoryResource,
expenseResource: expenseResource
}
});

Related

Restangular GET request returns 100 records only

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']);
});
}
});

Promises - I get the same result after $q.all

I have this code:
return WordPress.getAllCategories()
.then(function (cats) {
var category = {};
$q.all(cats.data.map(function (cat) {
return WordPress.getLatestPostOfCategory(cat.id)
.then(function (post) {
return WordPress.getMediaById(post.data.featured_media)
.then(function (media) {
console.log('post id: ' + post.data.id);
console.log('Post title: ' + post.data.title.rendered);
category.post = {};
category.post.id = post.data.id;
category.post.title = post.data.title.rendered;
category.post.content = post.data.content.rendered;
var splitted = category.post.content.split('<p><!--more--></p>');
category.post.introAsHtml = splitted[0];
category.post.contentAsHtml = splitted[1];
category.post.thumbnail = media.data.source_url;
return category;
});
});
})).then(function (res) {
console.log(res);
});
});
To load latest articles from each category for a magazine main page (using WordPress REST api with $http requests). The process is as follow:
1. Load all categories.
2. Get latest post from each category.
3. Get the media of the latest post.
4. Build the category.post object based on the post data and add the thumbnail from the media received (post-specific).
5. After all promises are resolved, $scope.categories = categories to apply for view.
The problem:
With the code above, I can see the console logs search for different posts and medias properly, but at the end I get an array containing the categories, all posts are the same. Same title, content, thumbnail image and everything.
What am I doing wrong with the promises here?
P.S. All WordPresss service functions work properly. They return a resolved promise after receiving the necessary data via $http requests from the WordPress blog.
Regards.
Try this way:
return WordPress.getAllCategories()
.then(function (cats) {
$q.all(cats.data.map(function (cat) {
return WordPress.getLatestPostOfCategory(cat.id)
.then(function (post) {
return WordPress.getMediaById(post.data.featured_media)
.then(function (media) {
console.log('post id: ' + post.data.id);
console.log('Post title: ' + post.data.title.rendered);
var category = {}; // moved declaration here to return new instance each time
category.post = {};
category.post.id = post.data.id;
category.post.title = post.data.title.rendered;
category.post.content = post.data.content.rendered;
var splitted = category.post.content.split('<p><!--more--></p>');
category.post.introAsHtml = splitted[0];
category.post.contentAsHtml = splitted[1];
category.post.thumbnail = media.data.source_url;
return category;
});
});
})).then(function (res) {
console.log(res);
});
});
You were returning same category object instance, I just create new instance every time inside getMediaById callback

Angular JS CRUD update not refreshing

My view is not getting reflected after the update/Delete/Create
My List page is EmpList. My update page is EmpDetail.
Here is my controller
$scope.UpdateEmp = function () {
var empl=$scope.Employee;
empFactory.empUpdate.update({ EmpID: $routeParams.EmpID, empval: empl });
$location.path('/EmpList');
};
Here is my Service
var resource = {
empUpdate:
$resource('../../Employee/PutEmployee/:EmpID', { EmpID: '#EmpID', empval: '#empl' }, { update: { method: 'PUT', isArray: true } })
}
return resource;
Here is my MVC controller
[HttpPut]
public JsonResult PutEmployee(int id, Employee empval)
{
empval.EmpID = id;
int index = emp.GetEmployees().FindIndex(i => i.EmpID == empval.EmpID);
emp.GetEmployees().RemoveAt(index);
emp.GetEmployees().Add(empval);
return Json(emp.GetEmployees(), JsonRequestBehavior.AllowGet);
}
MVC controller is getting called and the data is getting updated correctly, but it's not getting reflected in the main page
Note: In Emplist.html, I have the controller mapped where I m doing the query part to reflect the changes. The URL is not redirected to EmpList at all.
$scope.Employees = empFactories.query(function () {
console.log($scope.Employees);
});
You're sending the data but not using the reply:
reply = empFactory.empUpdate.update({ EmpID: $routeParams.EmpID, empval: empl });
Now you can assign the reply to your $scope

AngularJS reload data after PUT request

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);
}
});
};

Jaydata toLiveArray() error "Pure Class" w/ IndexedDB provider

Using Jaydata, I can populate my simple local database from an odata service. The database has an Organization table.
I am also using AngularJs. The following code gets the organizations from the local database and binds them to $scope.Organizations which is referenced on my OrganziationIndex view. I've tested this so far in Chrome, Safari on iOS7, and the Android browser built in to ICS, and it works as expected in each of those browsers.
var localDB = new InspecTechDB({
name: 'local',
databaseName: 'InspecTech'
});
app.controller('OrganizationIndex', function ($scope, $data) {
$scope.organizations = [];
//wait until the localDB is ready, then get the Organizations
$.when(localDB.onReady())
.then(function () {
$scope.inspectechdb = localDB;
$scope.organizations = localDB.Organizations.toLiveArray();
$scope.message = "Organizations fetched from local store. Click one of them!";
});
});
However, in IE11, I get an error message on the console that states simply "Pure Class" on this line and the organizations are not listed on the view:
scope.organizations = localDB.Organizations.toLiveArray();
A Google search reveals literally no results: Google Search
I've verified with console logging that the table is populated from the odata service. What I have found is that if I change the code as shown below (changed from local database to odata service), that the error goes away:
var remoteDB = new InspecTechDB({
name: 'oData',
oDataServiceHost: '/odata'
});
app.controller('OrganizationIndex', function ($scope, $data) {
$scope.organizations = [];
//wait until the localDB is ready, then get the Organizations
$.when(remoteDB.onReady())
.then(function () {
$scope.inspectechdb = remoteDB;
$scope.organizations = remoteDB.Organizations.toLiveArray();
$scope.message = "Organizations fetched from local store. Click one of them!";
});
});
I do intend for the application to be run offline so I need to be able to get the organizations from the local database and not the odata service.
Can someone point in the right direction for what I need to do to make this work in IE?
Thanks,
Mike
UPDATE 1:
I'm observing the same error in Firefox.
UPDATE 2:
I'm observing the same error in Chrome if I change the provider like so:
var localDB = new InspecTechDB({
name: 'indexedDb',
databaseName: 'InspecTech'
});
So the problem is not specific to IE, more like specific to the IndexedDB provider.
UDPATE 3:
Here's some workaround code. I'd still like to know about the problem with .toLiveArray().
var localDB = new InspecTechDB({
name: 'local',
databaseName: 'InspecTech'
});
app.controller('OrganizationIndex', function ($scope, $data) {
$scope.organizations = [];
//wait until the localDB is ready, then get the Organizations
//$.when(localDB.onReady())
//.then(function () {
// $scope.inspectechdb = localDB;
// $scope.organizations = localDB.Organizations.toLiveArray()
// .then(function () {
// $scope.message = "Organizations fetched from local store. Click one of them!";
// });
//});
//this code replaces the above code since I can't make toLiveArray work w/ indexedDB provider
$.when(localDB.onReady())
.then(function () {
var organizations = localDB.Organizations.toArray();
return $.when(organizations)
.then(function (orgs) {
$scope.$apply(function () {
orgs.forEach(function (organization) {
$scope.organizations.push(organization);
});
});
});
});
});

Resources