Not able to fetch employee details in web api using angularjs - angularjs

Hi I am developing one web api application using angularjs. I am doing one small crud operation. I am not able to hit to controller when debugging. Below is my controll.js code.
$scope.EditSubscriber = function (sub) {
var servCall = UserCreation.getSubsbyID(sub.user_id);
servCall.then(function (d) {
$scope.user_email = d.user_email,
$scope.user_password = d.user_password
}, function (error) {
console.log('Oops! Something went wrong while fetching the data.')
});
}
Below is my service.js code.
this.getSubsbyID = function (user_id) {
return $http({
method: 'get',
data: JSON.stringify(user_id),
url: 'api/User_Creation/' + user_id,
contentType: "application/json"
});
}
This is my controller code.
public IEnumerable<Noor_Users> Get(int user_id)
{
return entityObject.Noor_Users.Where(a => a.user_id == user_id).AsEnumerable();
}
I am not getting any error but I am not able to hit breakpoint in controller. May I know where I am doing wrong? Thank you all.

Related

PUT request in node.js using $http

I'm trying to make a PUT request to a SQL database through node.js using AngularJS. I keep getting a 400 bad request error. Not sure what's wrong with the request, since this format works using a straight $.ajax call. Any help would be appreciated
vm.approveUser = function(user_id){
console.log('in approveUser');
console.log('user_id', user_id);
$http({
method: 'PUT',
url: '/admin/approve',
data: user_id
}).then(function(){
console.log('back from the /approve');
vm.getRequests();
}); //end .then function
}; //end approveUser
Try simplifying the request and add a return statement. See if it resolves.
vm.approve = function(user_id) {
var url = '/admin/approve';
return $http.put(url, user_id)
.then(function(resp) {
vm.getRequests();
})
.catch(function(error) {
})
.finally(function() {
});
};

Best way to compare two API calls in angularJS?

I have an AngularJS frontend to my API-based application. There are services which make API calls, such as the following. I want to compare a variable from each of these calls:
Get the user data:
this.getUserData = function () {
var apiCall = $http({
method: 'GET',
url: 'http://example.com/api/userdata',
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('token'),
'Access-Control-Allow-Origin': 'Any'
}
});
return apiCall;
};
Get the page data:
this.getPageData = function(slug){
var apiCall = $http.get('http://example.com/api/public/page?slug=' + slug, {
headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') }
}
)
return apiCall;
};
In my controller I wish to compare a var from each of these calls, like so :
if (apiService.getUserData.likes.page_id == apiService.getPageData.page_id){ // do stuff }
What is the most efficient way of doing this, given that API calls can take a while.. I don't have to make an API call everytime I want to access a variable from the API do I? Bear in mind that these API calls would normally be made in DIFFERENT controllers, so the results are stored in different scopes.
Basically, I'm confused whether that bit of logic should go in a controller, in the service itself, or somewhere else. Any advice is appreciated. Thanks.
If you are comparing them in a controller you can easily call one followed by the other and compare. Since you say you have an "API-based application" and use an auth token from localStorage you should call the API in each different controller you have in case your auth token expires or something.
I would most likely create a service like (flushing it out to more to show all pieces):
angular.module('app').service('CompareService', CompareService);
CompareService.$inject = ['apiService', '$q'];
function CompareService(apiService, $q) {
return {
arePageIdsEqual: apie
};
function apie() {
var deferred = $q.defer();
apiService.getUserData().$promise.then(function(userData) {
apiService.getPageData().$promise.then(function(pageData) {
deferred.resolve(userData.likes.page_id === pageData.page_id);
}, function(err) {
deferred.reject(err);
});
}, function(err) {
deferred.reject(err);
});
return deferred.promise;
}
}
And in your controller just inject it and call it like:
CompareService.arePageIdsEqual(function(yes) {
if(yes) {
// do something
}
}, function(err) {
// err making the calls
});
You should implement it with a Promise.all.
function doCompare(userData,pageData){
if (userData.likes.page_id == pageData.page_id){
// do stuff
}
}
var promises = [apiService.getUserData,apiService.getPageData]
$q.all(promises).then(doCompare);

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

$http.post in angularjs not work to me and $http.get has response errors

I am new to angularjs am tying to learn it but some problems faced me, actually they are two problems:
First Problem: $http.post never works as there is no action and there is no response. However, $http.get is able to work.
Second Problem: Because of the first problem I call my restful webservice by $http.get, but the web service response status always is -1. Though the web service is able to do its work successfully and always response data null, can any one help me.
this my angular part:
var app = angular.module('myLogin',[]);
app.controller('loginController',function($scope,$http){
$scope.login=function(){
var username = $scope.username;
var password = $scope.pass;
$http.get("http://localhost:8080/spring/webservice/login/"+username+"/"+password)
.success(function(data,status){
alert("data : "+data);
alert("Data Inserted Successfully");
window.location.href = "chatScreen.html";
})
.error(function(data,status){
alert("Status: "+status);
window.location.href = "login.html";
});
}
});
and this my web service:
/**
* web service part
*/
#RequestMapping(value="webservice/login/{name}/{pass}", method=RequestMethod.GET)
#ResponseStatus(value = HttpStatus.OK)
public ResponseEntity<String> weblogin(#PathVariable("name") String name, #PathVariable("pass") String pass)
{
System.out.print("username : "+name);
System.out.print(pass);
UserService service = new UserService();
List<UserBean> users = service.getUsers();
if(users!=null)
{
for(UserBean user : users)
if( ( user.getUsername().equals(name) ) && ( user.getPassword().equals(pass) ) )
{
System.out.print("success");
username = name;
//model.addAttribute("result", "Welcome to chat..");
MessageService messageService = new MessageService();
List<MessageBean> messages = messageService.getMessage(username);
String userMessages="";
if(messages != null)
{
for(MessageBean msg : messages)
userMessages +="\n"+msg.getSender() + ": " + msg.getMessage()+" \n";
}
else
userMessages +="You have no Messages !";
//model.addAttribute("whoSendToMe", userMessages);
return new ResponseEntity(HttpStatus.OK);
}
}
return new ResponseEntity<String>("faild", HttpStatus.NOT_FOUND);
}
refer this may be this will give you idea how to approach your problem:-
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this is asynchronous call back
// you will get your data here comming from rest
}, function errorCallback(response) {
// called asynchronously if an error occurs
});
share your code so we will try to solve it
If you use method GET and you receive a -1 returned, it means normally that you are giving a wrong URL.
As for then POST method you should use this syntax:
return $http({
method: 'POST',
url: 'index.php/email/createDeliverable',
data: $.param({
csrfTokenName: --your token--,
userName: user.name,
password: password
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
Remember to add the headers part.
Your server may need a CSRF token validation, in this case you need to pass it, see un my example: csrfTokenName: --your token--,

angularjs not get data from woocommerce rest api

Sorry to say I am new in REST-API and authentication.
I am writing an application on angularjs using yomen. I want to get data using woocommerce rest api from wordpress. I am working on my computer local node server
I have write my controller
/*get the function from phpjs*/
function rawurlencode(str) {
str = (str+'').toString();
return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
replace(/\)/g, '%29').replace(/\*/g, '%2A');
}
var oauth = OAuth({
consumer: {
public: 'ck_my_customer_key',
secret: 'cs_my_customer_secret'
},
signature_method: 'HMAC-SHA1'
});
var request_data = {
url: 'http://biswas-stall.com/wc-api/v1/products',
method: 'GET',
};
var data = oauth.authorize(request_data);
var url =rawurlencode(request_data.url) + "&" +
"oauth_consumer_key"+"%3D"+rawurlencode(data.oauth_consumer_key)+
"%26"+"oauth_nonce"+"%3D"+rawurlencode(data.oauth_nonce)+
"%26"+"oauth_signature_method"+"%3D"+rawurlencode(data.oauth_signature_method)+
"%26"+"oauth_timestamp"+"%3D"+rawurlencode(data.oauth_timestamp)+
"%26"+"oauth_signature"+"%3D"+rawurlencode(data.oauth_signature);
$http.get(url).success(function(data) {
console.log(data);
})
I am using https://github.com/ddo/oauth-1.0a this library for my authentication.
I am getting 404 Not Found massage. What is my wrong. Can any one help me?

Resources