AngularJS using $resource - angularjs

I have an issue, i use my service that has GET and POST method. I try to update an select component on view. So when i try to add a new item, and click on button, which trigger a POST of new object, and what i want is to recieve updated list with my GET method, but it doesn't work. In only works if i refresh the page. I guess there is something wrong with callback
Here is the code i use:
Controller
$scope.addSubject = function(){
var newSubject = {"subjectName" : $scope.subjectType};
InterpelationSubjectFactory.create(newSubject);
/* Calling query method to update subjectType list */
InterpelationSubjectFactory.query(function(response){
$scope.subjectTypes = response;
});
console.log($scope.subjectTypes);
//$scope.selectedSubjectType = $scope.subjectType;
$scope.hideSubjectForm = true;
$scope.subjectType = '';
/*console.log(newSubject);*/
}
Service
services.factory('InterpelationSubjectFactory', function($resource){
return $resource(baseUrl + '/subjectTypes', {}, {
query: { method: 'GET', isArray: true},
create: { method: 'POST'}
})
});
Can please someone point me where i did wrong?
Thanks

For the callback, you only have the one in case of success. Can you please add the one that handles error and display the error message? That should give us a clue.
InterpelationSubjectFactory.query(function(response){
// success handler
$scope.subjectTypes = response;
}, function(error) {
// error handler
console.log("Error InterpelationSubjectFactory.query: " + JSON.stringify(error));
}
);
Please share the error message.

Related

Display Please wait or processing message to user once the form is filled in AngularJS

I am creating a registration form in AngularJS, wherein once the admin fills the form and on submit, I am doing two things: 1. Saving the data into the DB. 2. Sending an email to the person with his username and password. So on submitting my application is taking some time (around 5-7 seconds) to post the success message back on the screen. So I want to show some message while these background operations complete. I need your help as I am new to AngularJS.
createUserService.Register(obj, function(data) {
if (data.error) {
console.log("Check " + data.error);
} else {
alertify.alert("Successfully Registered");
$state.reload();
}
This is my service:
function Register(obj, callback) {
$http({
method : 'POST',
url : '/api/addUserOps',
data : obj
}).then(function(response) {
callback(response.data);
}, function(error) {
callback(error);
});
}
});
You can try this way.
Service function
function Register(obj) {
return $http({
method : 'POST',
url : '/api/addUserOps',
data : obj
});
}
Calling your function
// Trying using https://github.com/cgross/angular-busy for showing a loader here.
createUserService.Register(obj)
.then(function(data){
// stop your loader here with a success message.
})
.catch(function(error) {
// your error message here.
})
Hope you find this useful.

How to post data on button click using AngularJS

I have an application made with .NET core framework and pure html in the front end. I was using AJAX to post and get data.
I am new to Angular and decided to convert the front end of the application to Angular for learning purposes.
For Example, I have a button that will change the state of employees from 'Billed' to 'Available' state. The ID for available state is defined in the back end and it is '1'.
//MOVE TO BENCH BUTTON CLICK
$(document).ready(function()
{
var allVals = [];
$("#MoveToBench").click(function()
{
$('input:checkbox:checked').each(function () {
allVals.push($(this).val());
});
for (i = 0;i<allVals.length;i++){
PostBenchList(allVals[i])
}
function PostBenchList(entityId) {
var data = 'entityID='.concat(entityId).concat('&nextStateId=1');
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:1783/api/Workflow?"+data,
data: data,
dataType: "text",
success: function (data) {
location.reload();
alert("Successfully added the selected Employees to TalentPool");
},
fail: function (error) {
Console.Log(error);
}
})
}
});
});
The above code is taking an array of entityID's as input. For the Angular application, the array is not required as only one entity ID will be passed.
The API controller in the backend is :
// POST api/values
[HttpPost]
public void Post(int entityId, int nextStateId)
{
JObject jsonObject = JObject.Parse(System.IO.File.ReadAllText("Config.Json"));
string jsonFile = jsonObject.GetValue("WorkfowJsonFileLocation").ToString();
var nextState = _stateServices.Get(nextStateId);
var handler = new WorkflowHandler(nextState, jsonFile, _entityServices, 1, _stateServices, _subStateServices, _appServices);
handler.PerformAction(entityId);
}
The above code worked for me and it would change the state ID of the employee(EntityID)to 1(nextStateId)
Now I have a button in AngularJS and I want it to do the same action. How would I achieve this? As I am still in the procedure of learning, I don't have a clue how to do this. Can anyone help me to achieve this? This would help me to learn and do all similar buttons.
Thank You.
You can use ng-click and call a function to post the data,
HTML:
<button ng-click="PostData()">
Click to POST
</button>
Controller:
app.controller('PostController',['$scope',function($scope)
{
$scope.sendPost = function() {
var data = $.param({
json: JSON.stringify({
name: $scope.newName
})
});
$http.post("/echo/json/", data).success(function(data, status) {
$scope.hello = data;
})
}
}]);
DEMO APP

Query: Response does not match configured parameter

i am getting response error please any one try to solve my problem. i am trying to solve that but i didn't solve this. please help me.
thanks in advance
$scope.init = {};
var Call = $resource('../api/Home', {}, { query: { method: 'POST', isArray: false} });
$scope.init = function () {
//alert("hi");
$scope.selected = "";
var x = $('#txtSearch').val();
var _ReqObj = new Object();
_ReqObj.id = x;
_ReqObj.Meth = "GJ";
Call.query({}, _ReqObj,
function (response) {
alert(response);
alert(_ReqObj);
if (response == '') {
// alert('no data');
window.location.replace("index.html");
}
else {
//$scope.click = response;
$scope.init = response;
}
},
function (error) {
window.location.replace("index.html");
}
);
};
The error message says: "Expected response to contain an object but got an array"
this means: Your request (Call.query) does expect a single object (you are setting isArray: false). But the server sends an array. So the server is not sending what the function expects!
There is some hints I want to give you:
Why are you using query? A query is normally used to get an array from the server, not a single object. Why are you using query at all?
Do you really want a single object or do you want a list of objects?
What is the server sending? Open the development console in your browser (ctr+alt+I in Chrome) and click on the Network tab. Click on the request (../api/Home) and check the response from the server. You should see the json objects or arrays the server sent as a response to your request.

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

Angular.js delete resource with parameter

My rest api accpets DELETE requests to the following url
/api/users/{slug}
So by sending delete to a specified user (slug) the user would be deleted. here is the service code:
angular.module('UserService',['ngResource']).factory('User', function($resource){
var User = $resource('/api/users/:id1/:action/:id2', //add param to the url
{},
{
delete_user: {
method: 'DELETE',
params: {
id1:"#id"
}
},
update: {
method: 'PUT',
params: {
id1:"#id"
}
}
});
return User;
});
I call the delete function via
user.$delete_user({id:user.id}, function(){}, function(response){});
However the request seems to be send to the wrong url.
/api/users?id=4
So the parameter is actually missing, as a result I get a 405 Method not allowed. Is there any chance to send the delete request in the style of my api?
params is an object of default request parameteres in your actions. If you want url parameters you have to specify them in the second parameter like this:
angular.module('UserService',['ngResource']).factory('User', function($resource){
var User = $resource('/api/users/:id1/:action/:id2', //add param to the url
{id1:'#id'},
{
delete_user: {
method: 'DELETE'
}
});
return User;
});
this works with either:
// user has id
user.$delete_user(function(){
//success
},function(){
// error
});
or
var data = {id:'id_from_data'};
User.delete_user({},data);
or
var params = {id1:'id1_from_params'};
User.delete_user(params);
I've made a plnkr-example - you have to open your console to verify that the DELETE requests are correct.
See parameterDefaults in the Angular resource documentation.
I had this problem for a while I was using a service to add / delete / update categories. While passing in params for get it worked fine but then when deleting it was giving me a ?id=1234 instead of api/resource/1234
I got around this by making the default param a string.
///Controller
Service.delete({categoryId:id}, function(resp){
console.log(resp)//whatever logic you want in here
});
//SERVICES
$resource('api/resource/:categoryId', {"categoryId":"#categoryId"}, {
query:{method:"GET"},
delete:{method:"DELETE"},
});
Should work and the resulting url will be, originally I had categoryId in the default params as a variable name.
api/resource/1234 etc
Just omit the '#' in the parameter
.factory('reportFactory', ['$resource', 'baseUrl', function ($resource, baseUrl) {
return $resource(baseUrl + '/keys/:id', {}, {
delete: { method: 'DELETE',
headers: {
'Content-Type': 'application/json'
},
params: {id: 'id'} }
})
}]);
this will give you:
http://localhost:8080/reports/api/keys/b8a8a8e39a8f55da94fdbe6c
without the question mark
If you want to delete a model, there's no need to add params (params does not work for DELETE anyway):
$resource('/users/:id').delete({id: user.id}, function(res) {
...
})
or
$resource('/users/:role/:id').delete({role: 'visitor', id: user.id});
I'm not sure if it's a bug of ngResource.

Resources