I am new to angularJS. I am using ionic framework for android application development. In my project I am calling webservice and getting its response and attaching that response to scope variable to get data on the view. First time webservice called and updates the view as expected but when I call the service again that is not updating my data. It seems as ng-repeat is not working due to some reference loosing problem. But I am not able to find out the solution of that. Although I have tried different solution via using apply() as was mentioned in one of the stack overflow posts. Below is the code of attaching web-service response to the scope variable.
$http(req).then(function (response) {
if (response.data.IsSuccess) {
console.log("data = " + JSON.stringify(response.data));
console.log('Response is '+response.data.IsSuccess);
$scope.companies = response.data.Response.Companies;
}
and below is the line of code using to update the view
<div class="col col-100" ng-repeat="company in companies">
any help or advice
Below is the login code that is calling webservice to update my data
function callLogInService(userName, password){
console.log("user name is " +userName);
console.log("password is " + password);
var req = {
method: 'POST',
url: ApiUrl + '/api/User/LoginUser',
headers: {
'Content-Type': 'application/json'
},
data: {
Email: userName,
Password: password
}
}
$ionicLoading.show({
template: 'Signing in...'
});
$http(req).then(function (response) {
if (response.data.IsSuccess) {
console.log("data = " + JSON.stringify(response.data));
console.log('Response is '+response.data.IsSuccess);
var userID = response.data.Response.AppUserId;
var userName = response.data.Response.AppUserName;
setUserName(userName);
setUserId(userID);
$rootScope.appUserName;
var userIdFromSession = getUserID;
if(undefined == $rootScope.companyIdForSubscription
|| $rootScope.companyIdForSubscription == 0){
console.log("id is undefined for subscription");
} else {
console.log("company subscription id is " + $rootScope.companyIdForSubscription);
$scope.subscribe($rootScope.companyIdForSubscription);
}
$scope.close();
$scope.setVisibilityOdSideMenuIcons();
$scope.getAllCompanies();
}
else {
showErrorAlertDialogue(response.data.ErrorMessage);
}
}, function (reason) {
console.log('reason is ' + reason.data);
$log.info('reasonf log is' + reason) ;
showErrorAlertDialogue("Please check your internet connection.");
}).finally(function () {
console.log("finally is called");
$ionicLoading.hide();
$ionicPopup.close()
});
}
$scope.getAllCompanies(); this line is calling service again
Related
I am new to angular-js and building a simple to-do application. I am creating a task and displaying the created task in a html table using ng-repeat. But the problem is that after posting the data, $scope.tasks variable is updated on controller side, but not in view. The view updates after refreshing the web page only and the task is added to html table. How can I make the view update after creating the task. Thanks in advance. Here is my code:
In my controller:
var app = angular.module('MyApp', ['ngMaterial', 'ngMessages']);
app.controller('DemoCtrl', function($scope,$mdSidenav,$mdDialog,$interval,$http,$mdToast) {
$scope.tasks = [];
_refreshTaskData(); //initial refresh
$scope.submitForm = function() {
var description = "";
var taskId = "";
$scope.formData = {
taskId: $scope.taskId,
description: $scope.description,
};
$http({
method: "POST",
url: 'savetask',
data: angular.toJson($scope.formData),
headers : {
'Content-Type': 'application/json',
}
}).then(_success, _error);
};
function _refreshTaskData() {
$http({
method : 'GET',
url : 'getTask',
}).then(function(res) { // success
$scope.tasks = res.data;
}, function(res) { // error
console.log("Error: " + res.status + " : " + res.data);
});
}
function _success(res) {
$mdDialog.hide();
console.log('in success function');
_refreshTaskData(); ;
}
function _error(res) {
//error handling
}
});
In my view:
<table>
<tr ng-repeat=" t in tasks">
<td>{{t.id}}</td>
<td>{{t.description}}</td>
</tr>
</table>
You must understand that these JS frameworks are asynchronous. Now what happens is, if you do an API call and make another API call whose result is based on the first one, the console does not wait for the result from one API and directly moves forward. SO what's happening in your case is sometimes/many times, before the POST call is served, the controller is not able to get fresh data with GET in time, thus not updating the view. What you can possibly do is enforce the GET only when POST is served
$http({
method: "POST",
url: 'savetask',
data: angular.toJson($scope.formData),
headers : {
'Content-Type': 'application/json',
}
}).then(function(res){
$http({
method : 'GET',
url : 'getTask',
}).then(function(res) { // success
$scope.tasks = res.data;
}, function(err) { // error
console.log("Error: " + err.status + " : " + err.data);
});
});
It would be best if you are sending a success message from the backend and checking before GET call
I think you are not calling _refreshEmployeeData at any point of time. If you add that instead of _refreshTaskData in your JS, then you will be able to see the result in view.
Also kindly use ng-init to call the _refreshEmployeeData in the controller. That would be the best way to initialize the fields.
A follow-up on a similar question I posted yesterday. I am trying to delete data from a table in Azure App service. This is my function in my Angular file.
function delName(user) {
//$scope.categories.push(user);
alert("about to delete. Action cannot be undone. Continue?")
$http.delete('https://test-evangelists-1.azurewebsites.net/tables/people', user, config)
.then(function (res) {
$scope.getNames();
});
}
Then I added an HTML button:
<button id="btn-del-evangelist" class="btn btn-default btn" ng-click="delName(user);">Delete User</button>
This is the value of my headers variable:
var config = {
headers: {
'Access-Control-Allow-Origin':'*',
'ZUMO-API-VERSION': '2.0.0'
}
};
But when I tried to run it, the console returns the following error:
which states that the header for ZUMO-API-VERSION must be specified.
Below is my code for GET and POST
GET:
function getNames() {
$http.get('https://test-evangelists-1.azurewebsites.net/tables/people', config)
.then(function (res) {
console.log(res);
$scope.people = res.data;
});
}
POST
function addName(user){
//$scope.categories.push(user);
alert("about to post!")
$http.post('https://test-evangelists-1.azurewebsites.net/tables/people', user, config)
.then(function (res) {
$scope.getNames();
});
}
Since I have already specified the header in my variable, I wonder what can be wrong here. Any help will be appreciated.
UPDATE:
I figured out that the Id must be appended to the URL before I can perform delete. However, I need to run a GET to retrieve the ID given the parameters but I am still encountering errors when getting the ID.
This is now my Delete function
function delName(user) {
alert("About to delete. Action cannot be undone. Continue?")
var retrievedId = "";
$http.get('https://test-evangelists-1.azurewebsites.net/tables/people', {
params: { name: user.name, location: user.location },
headers: { 'Access-Control-Allow-Origin': '*', 'ZUMO-API-VERSION': '2.0.0' }
})
.then(function (res) {
retrievedId = res.id;
alert(retrievedId);
});
$http.delete('https://test-evangelists-1.azurewebsites.net/tables/people/' + retrievedId, config)
.then(function (res) {
$scope.getNames();
});
}
Does anyone know what is wrong in the GET command when getting the ID?
UPDATE 2: I have written instead an Web Method (asmx) that will connect to SQL server to retrieve the ID passing the needed parameters. The ID will be returned as a string literal but in JSON format. Then I called JSON.parse to parse the string into JSON object then assigned the ID to a variable to which I appended in the URL. –
This is now my Delete function after I have written the Web Method.
function delName(user) {
var confirmres = confirm("You are about to delete this record. Action cannot be undone. Continue?");
var retrievedId = "";
if (confirmres == true) {
//get the ID via web service
$http.get('\\angular\\EvangelistsWebService.asmx/GetId', {
params: { name: user.name, location: user.location },
headers: { 'Access-Control-Allow-Origin': '*', 'ZUMO-API-VERSION': '2.0.0' },
dataType: "json",
contentType: "application/json; charset=utf-8"
})
.then(function (res) {
$scope.retData = res.data;
var obj = JSON.parse($scope.retData);
angular.forEach(obj, function (item) {
if (item.length == 0)
alert('No data found');
else {
//perform delete after getting the ID and append it to url
$http.delete('https://test-evangelists-1.azurewebsites.net/tables/people/' + item.id, config)
.then(function (res) {
$scope.getNames();
});
alert(item.id + ' deleted');
}
});
});
}
}
That is one way that I have learned on how to call HTTP DELETE on AngularJS. But I don't know if that is the optimal one. In any case, that works for me, unless there will be other suggestions.
$http.delete only has one parameter (config), not two (data, config).
Delete API
delete(url, [config]);
vs.
Post API
post(url, data, [config]);
To your updated problem:
To delete an item from your table, it appears the correct url is:
/tables/tablename/:id
Note the : before id.
Inside my controller I have a call to fetch a document from my back end that looks like this:
orderFactory.query({_id: $stateParams.obj}).$promise.then(
function (response) {
console.log(response);
$scope.invoice = response[0].invoice;
$scope.client = response[0].client;
$scope.orderdetails = response[0].orderdetails;
},
function (response) {
console.log(response);
$scope.message = "Error: " + response.status + " " + response.statusText;
});
But the problem is that this code sends a GET request to /orders&_id=5926bef0f5344c1ff8a9b295 but the REST end point it should access is /orders/5926bef0f5344c1ff8a9b295
The URL in the browser is /trackdetails and I cant use $stateParams to access the end point desired
So my question is there any way to access that end point from the controller? Or perhaps I have to rework my architecture?
In resource:
$resource('your_url/:_id',
{
_id: '#_id'
}
)
In component:
orderFactory.get({_id: $stateParams.obj}, function(response) {
// success
}, function(reject) {
// error
})
I have a problem with a function, when I ran it I got error:
PUT http://10.10.3.20:8082/oct/activite/updateStatus/4 401 ()
error_description
:
"Full authentication is required to access this resource"
this is my function in back-end with spring boot:
service:
#Override
public boolean MajStatus(Long id) {
Activite ac = activiteRepository.findOne(id);
ac.setStateActivite(true);
activiteRepository.saveAndFlush(ac);
return true;
}
ctrl:
#Secured({"ROLE_manager","ROLE_validateur"})
#RequestMapping(value="/updateStatus/{id}", method = RequestMethod.PUT)
public boolean MajStatus(#PathVariable("id") Long id) {
return activiteMetier.MajStatus(id);
}
in front-end I use AngularJS
ctrl:
$scope.MajStatus = function (index) {
var authorization = "Bearer " + $sessionStorage.get('access_token');
var config22 = {
headers: {
'Content-Type': 'application/json',
'Authorization': authorization
}
};
$scope.activiteStatus={};
$http.put(prod.url3+"/activite/updateStatus/"+index,config22)
.success(function(response){
$scope.activiteStatus = response;
$state.reload();
SweetAlert.swal({
title: 'Status expired',
text: 'I will close in 2 seconds.',
timer: 2000
});
})
.error(function(response){
$scope.data = response.statusText;
});
return $scope.activiteStatus;
};
in my page html:
<td ng-click="$event.stopPropagation(); MajStatus(p.idActivite)"
ng-if="p.stateActivite==false" class="hidden-xs">
<span class="label label-sm label-success">Active</span></td>
I have problem just with this function, other functions of CRUD works fine and I'm in connect with user that have ROLE_manager.
I did test the function in back-end using 'Advanced REST client' and it works fine.
The problem is in front-end. So please I need your help.
Thanks in advance :)
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--,