Fetching data from server with promise using angularjs - angularjs

How do I fetch table from db with promise. I have created a service and http call with promise. I have checked the console and the url is not getting called. I am not sure this is the eight way of creating service return a http promise
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<base href="/">
<title>The Single Page Blogger</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script data-require="ui-bootstrap#*" data-semver="0.12.1" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.1.min.js"></script>
<script src="<%=request.getContextPath()%>/js/module.js"></script>
<link rel="stylesheet" href="<%=request.getContextPath()%>/style2.css" />
<script>
app.controller('tableController', function ($log, $scope, tableService)
{
$scope.customerTable = [];
var promise = tableService.fetchTable();
promise.then(function (data)
{
console.log("Your name is: " + data);
$scope.customerTable = data;
});
});
app.factory('tableService', function ($http)
{
return
{
fetchTable: function()
{
return $http.get('<%=request.getContextPath()%>/GetTable.do');
}
}
});
</script>
</head>
<body>
<div class="container" id="main"><br/><br/>
Search: <input type="text" ng-model="search" placeholder="Search">
<div ng-controller="tableController">
<table class="table table-striped table-hover table-bordered">
<tr>
<th style="font-size: 13.3px">Card number</th>
<th style="font-size: 13.3px">First name</th>
<th style="font-size: 13.3px">Opening balance</th>
<th style="font-size: 13.3px">Withdrawal</th>
<th style="font-size: 13.3px">Deposit</th>
<th style="font-size: 13.3px">Closing balance</th>
<th style="font-size: 13.3px">Tx date</th>
<th style="font-size: 13.3px">Usage type</th>
</tr>
<tr ng-repeat="data in filteredTodos| filter: search">
<td>{{data.CARD_NUMBER}}</td>
<td>{{data.FIRST_NAME}}</td>
<td>{{data.OPENING_BALANCE}}</td>
<td>{{data.WITHDRAWAL}}</td>
<td>{{data.DEPOSIT}}</td>
<td>{{data.CLOSING_BAL}}</td>
<td>{{data.TXDATE}}</td>
<td>{{data.USAGE_TYPE}}</td>
</tr>
</table>
<pagination
ng-model="currentPage"
total-items="customerTable.length"
max-size="maxSize"
boundary-links="true">
</pagination>
<br/><br/><br>
<button class="form-control btn btn-success" type="submit" ng-click="fetchTable()">Load Table Data</button>
</div>
</div>
</body>
</html>

Your service makes the promise but does not deliver, try adding the $q service into yours like this:
app.factory('tableService', function ($http, $q) {
return {
fetchTable: function() {
// the $http API is based on the deferred/promise APIs exposed by the $q service
// so it returns a promise for us by default
return $http.get('<%=request.getContextPath()%>/GetTable.do')
.then(function(response) {
if (typeof response.data === 'object') {
return response.data;
} else {
// invalid response
return $q.reject(response.data);
}
}, function(response) {
// something went wrong
return $q.reject(response.data);
});
}
};
});
app.controller('tableController', function ($log, $scope, tableService)
{
$scope.customerTable = [];
$scope.getData = function() {
var promise = tableService.fetchTable();
promise.then(function (data)
{
console.log("Your name is: " + data);
$scope.customerTable = data;
});
}
});
<div ng-controller="tableController" ng-init="getData()">

app.controller('tableController', function ($log, $scope, tableService)
{
$scope.customerTable = [];
var promise = tableService.fetchTable();
promise.then(function (data)
{
console.log("Your name is: " + data);
$scope.customerTable = data;
});
});
This should do it. You were returning the data before setting the $scope.customerTable. As a matter of fact, why are you even returning data? You can't return something from a callback like that. I've removed that line also.

Related

Angular JS expression not evaluating using $http service

This is Script.js
var app = angular
.module("myModule", [])
.controller("myController", function ($scope, $http) {
$http.get(
url: 'EmployeeService.asmx/GetAllEmployees'
)
.then(function (response) {
$scope.employees = response.data;
});
});
This is Htmlpage1.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
<script src="Scripts/Script.js"></script>
</head>
<body ng-app="myModule">
<div ng-controller="myController">
<table border="1" style="border:none;">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Gender</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees">
<td>{{employee.id}}</td>
<td>{{employee.name}}</td>
<td>{{employee.gender}}</td>
<td>{{employee.salary}}</td>
</tr>
</tbody>
</table>
</div>
</html>
The expression Id Name Gender Salary
{{employee.id}} {{employee.name}} {{employee.gender}} {{employee.salary}} is not getting evaluated
The values of the table are not displaying
$http.get() method gets the url parameter as a string, so you are not using it correctly. This is the correct syntax:
$http.get('EmployeeService.asmx/GetAllEmployees')
Read more: $http#get
IF the url is correct then your code should work with this change
What event or who is making that request?
var app = angular
.module("myModule", [])
.controller("myController", function ($scope, $http) {
//when the page is ready
angular.element(document).ready(function() {
$http({ method: 'GET',
url: 'EmployeeService.asmx/GetAllEmployees'
}).then(function (response) {
$scope.employees = response.data;
}).catch(function (err) {
console.log('Error encountered : ' + err);
});
});
});

Angular controller is not invoked even with ng-app and ng-controller declaration

I am creating a web api with angular. I get a problem in my HTML code. If I just invoke the web api, I get the needed data, but when I try to print it out in my HTML, I do not get the result. Please check my codes below.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Angular CRUD</title>
<link href="Content/bootstrap.css" rel="stylesheet"/>
<script src="Scripts/angular.js"></script>
<script src="Scripts/jquery-1.10.2.js"></script>
<script src="Scripts/bootstrap.js"></script>
<script>
var app = angular.module('myApp', [])
app.controller("EmployeeCtrl", function ($scope, $http) {
getEmployees();
var getEmployees = function () {
alert("SDFS");
$http.get('/api/Employee')
.then(function (response) {
$scope.Employee = response.data
},
function () {
alert("Error in retrieving data");
})
}
})
</script>
</head>
<body ng-app="myApp" ng-contoller="EmployeeCtrl">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Employee ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Employee Code</th>
<th>Position</th>
<th>Office</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in Employee">
<td>{{item.EmployeeId}}</td>
<td>{{item.FirstName}}</td>
<td>{{item.LastName}}</td>
<td>{{item.EmployeeCode}}</td>
<td>{{item.Position}}</td>
<td>{{item.Office}}</td>
</tr>
</tbody>
</table>
</body>
</html>
You will notice that I even created an alert to check if the function is invoked but apparently it is not invoked. Can you please help. Thank you.
You have two issues with your code:
You have misspelled ng-controller.
You can not use the function before definition when creating function as a variable i.e. var funcName = function () { ... }. Change that to function getEmployees () { ... }
Solve these and it would work!
js code execute line by line you invoke your function before declare it
try this code instead of your controller:
<script>
var app = angular.module('myApp', [])
app.controller("EmployeeCtrl", function ($scope, $http) {
getEmployees();
var getEmployees=function() {
alert("SDFS");
$http.get('/api/Employee')
.then(function(response) {
$scope.Employee = response.data
},
function() {
alert("Error in retrieving data");
})
}
})
</script>

Display JSON response with Angularjs

I need to display data from JSON response using Angularjs
When checking the response with DevTools i can see the results, but when it comes to diplay, it doesn't work
Controller :
MovieApp.controller('movieAdminCtrl', ['$http', '$scope', function($http, $scope){
$scope.movies=[];
$http.get('http://localhost:3000/movies').success(function(data) {
$scope.movies = data;
});
}]);
Response :
Display Code :
<tbody ng-repeat="movie in movies" >
<td></td>
<td >{{movie.title}}</td>
<td >{{movie.actors}}</td>
<td >{{movie.Created_date}}</td>
<td><img ng-src="{{movie.poster}}" /></td>
You need to access the data property of the response
$http.get('http://localhost:3000/movies').success(function(data) {
$scope.movies = data.data;
});
Please try this code..
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body ng-app="app" ng-controller="movieAdminCtrl">
<table>
<tr ng-repeat="movie in movies">
<td></td>
<td>{{movie.title}}</td>
<td>{{movie.actors}}</td>
<td>{{movie.Created_date}}</td>
<td>
<img ng-src="{{movie.poster}}" />
</td>
</tr>
</table>
<script src="../lib/angular.js"></script>
<script>
var MovieApp = angular.module('app', []);
MovieApp.controller('movieAdminCtrl', ['$http', '$scope', function ($http, $scope) {
$scope.movies = [];
$http.get('http://localhost:3000/movies').success(function (data) {
$scope.movies = data;
});
}]);
</script>
</body>
</html>

Configure ngRoute with $http

I am trying to confugure ngRoute with $http and I am getting error in console when i go to website: localhost:8080
Uncaught ReferenceError: angularModule is not defined(anonymous
function) # item_controller.js:2
angular.js:38Uncaught Error:
[$injector:modulerr]
http://errors.angularjs.org/1.5.5/$injector/modulerr?p0=myApp&p1=Error%3A%2…2Flocalhost%3A8080%2Fbower_components%2Fangular%2Fangular.min.js%3A21%3A19)
When I open http://localhost:8080/home then I see "Whitable error page". I am writeing my API in Spring framework (Spring-boot)
How should I configure these two things to work properly? I cant find any good example how should i write this in good way.
My configuration looks like below:
app.js
'use strict';
var App = angular.module('myApp', ['ngRoute', 'moduleItemController']);
App.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when( '/home', {
templateUrl: '../item.html',
controller: 'ItemController'
}).
when('/item/:itemCode',{
templateUrl: '../../templates/item-detail.html',
controller: 'ItemController'
}).otherwise({
redirectTo: '/home'
});
}]);
item_controller.js
'use strict';
var moduleItemController = angularModule.module('moduleItemController',[])
moduleItemController.controller('ItemController', ['$scope', 'ItemService', function ($scope, ItemService) {
var self = this;
self.item = {id: null, itemCode: '', itemName: '', price: ''};
self.items = [];
self.fetchAllItems = function () {
ItemService.fetchAllItems()
.then(
function (d) {
self.items = d;
},
function (errResponse) {
console.error('Error while fetching Currencies');
}
);
};
self.createItem = function (item) {
ItemService.createItem(item)
.then(
self.fetchAllItems,
function (errResponse) {
console.error('Error while creating item.');
}
);
};
self.updateItem = function (item, id) {
ItemService.updateItem(item, id)
.then(
self.fetchAllItems,
function (errResponse) {
console.error('Error while updating item.');
}
);
};
self.deleteItem = function (id) {
ItemService.deleteItem(id)
.then(
self.fetchAllItems,
function (errResponse) {
console.error('Error while deleting item.');
}
);
};
self.updatePrice = function (newPrice, item, id) {
ItemService.updatePrice(newPrice, item, id)
.then(
self.fetchAllItems,
function (errResponse) {
console.error('Error while updating item.');
}
);
};
self.fetchAllItems();
self.submit = function () {
if (self.item.id === null) {
console.log('Saving New item', self.item);
self.createItem(self.item);
}
else {
console.log('Sth went wrong!');
}
self.reset();
};
self.remove = function (id) {
console.log('id to be deleted', id);
if (self.item.id === id) {
self.reset();
}
self.deleteItem(id);
};
self.reset = function () {
self.item = {id: null, itemCode: '', itemName: '', price: ''};
$scope.myForm.$setPristine();
};
}]);
moduleItemController.controller('ItemController', ['$scope','$routeParams', function ($scope,$routeParams) {
$scope.itemCode = $routeParams.itemCode;
}]);
item_service.js
App.factory('ItemService', ['$http', '$q', function ($http, $q) {
return {
fetchAllItems: function () {
return $http.get('http://localhost:8080/api/item/all')
.then(
function (response) {
return response.data;
console.success('Success');
},
function (errResponse) {
console.error('Error while fetching users');
return $q.reject(errResponse);
}
);
},
.
.
.
// other crud operations
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HOME</title>
<link rel="stylesheet" type="text/css" href="bower_components/semantic/dist/semantic.min.css">
<script src="bower_components/semantic/dist/semantic.js"></script>
<!--Angular dependencies-->
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/controller/item_controller.js"></script>
<script src="js/service/item_service.js"></script>
</head>
<body ng-app="myApp">
<div ng-view></div>
</body>
</html>
item.html -- here is part of this file where I want to use ngRoute
<table class="ui fixed table">
<thead>
<tr>
<th>Id</th>
<th>Code</th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th width="20%"></th>
<th width="20%"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="i in ictrl.items | filter:query">
<td><span ng-bind="i.id"></span></td>
<td class="selectable">
<span ng-bind="i.itemCode"></span>
</td>
<td><span ng-bind="i.itemName"></span></td>
<td><span ng-bind="i.price"></span></td>
<td><span ng-bind="i.quantity"></span></td>
<td>
<button class="negative ui button" ng-click="ictrl.remove(i.id)">delete</button>
</td>
<td>
<button class="ui secondary button">zp</button>
</td>
</tr>
</tbody>
</table>
item-detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Details</title>
<!--SEMANTIC-->
<link rel="stylesheet" type="text/css" href="bower_components/semantic/dist/semantic.min.css">
<script src="bower_components/semantic/dist/semantic.js"></script>
<!--ANGULAR-->
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-route/angular-route.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controller/item_controller.js"></script>
<script src="js/service/item_service.js"></script>
</head>
<body ng-app="myApp">
<div class="item table container">
<h1>TBD DETAILED VIEW FOR {{itemCode}}</h1>
</div>
</body>
</html>
The problem is you are trying to use angularModule instead of angular in item_controller.js. The global object from angular.js is angular and not angularModule
Change the below line as:
var moduleItemController = angularModule.module('moduleItemController',[]);
to
var moduleItemController = angular.module('moduleItemController',[]);
Line 2 of item_controller.js is referencing angularModule.module which is undefined. I think you want angular.module.

angular js not waiting for rest response

I am new to angular js. I have to work with the rest calls in java. I have taken an example related to angularjs, java rest.
see app.js
angular.module('ngdemo', ['ngRoute','ngdemo.filters', 'ngdemo.services', 'ngdemo.directives', 'ngdemo.controllers']).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/user-list', {templateUrl: 'partials/user-list.html', controller: 'UserListCtrl'});
$routeProvider.when('/user-detail/:id', {templateUrl: 'partials/user-detail.html', controller: 'UserDetailCtrl'});
$routeProvider.when('/user-creation', {templateUrl: 'partials/user-creation.html', controller: 'UserCreationCtrl'});
}]);
controllers.js
'use strict';
/* Controllers */
var app = angular.module('ngdemo.controllers', []);
app.run(function ($rootScope, $templateCache) {
$rootScope.$on('$viewContentLoaded', function () {
$templateCache.removeAll();
});
});
app.controller('UserListCtrl', ['$scope', 'UsersFactory', 'UserFactory', 'DeleteUserFactory', 'UsersSearchFactory', '$location',
function ($scope, UsersFactory, UserFactory, DeleteUserFactory, UsersSearchFactory, $location) {
// callback for ng-click 'editUser':
$scope.editUser = function (userId) {
$location.path('/user-detail/' + userId);
};
$scope.searchUser = function () {
$scope.users = UsersSearchFactory.search($scope.user);
};
// callback for ng-click 'deleteUser':
$scope.deleteUser = function (user) {
DeleteUserFactory.delete(user);
$scope.users = UsersFactory.query({startRow: 0}, {endRow: 75});
};
// callback for ng-click 'createUser':
$scope.createNewUser = function () {
$location.path('/user-creation');
};
$scope.users = UsersFactory.query({startRow: 0}, {endRow: 75});
}]);
app.controller('UserDetailCtrl', ['$scope', '$routeParams', 'UserFactory', 'UpdateUserFactory', '$location',
function ($scope, $routeParams, UserFactory, UpdateUserFactory, $location) {
// callback for ng-click 'updateUser':
$scope.updateUser = function () {
UpdateUserFactory.update($scope.user);
$location.path('/user-list');
};
// callback for ng-click 'cancel':
$scope.cancel = function () {
$location.path('/user-list');
};
$scope.user = UserFactory.show({id: $routeParams.id});
}]);
app.controller('UserCreationCtrl', ['$scope', 'CreateUserFactory', '$location',
function ($scope, CreateUserFactory, $location) {
// callback for ng-click 'createNewUser':
$scope.createNewUser = function () {
CreateUserFactory.create($scope.user);
$location.path('/user-list');
}
}]);
services.js
'use strict';
/* Services */
var services = angular.module('ngdemo.services', ['ngResource']);
services.factory('UsersFactory', function ($resource) {
return $resource('/ngdemo/rest/getUsers/:startRow/:endRow', {}, {
query: { method: 'GET', isArray: true, params: {startRow: '#startRow', endRow: '#endRow'} },
create: { method: 'POST' }
})
});
services.factory('UsersCountFactory', function ($resource) {
return $resource('/ngdemo/rest/getUsersCount', {}, {
count: { method: 'GET'}
})
});
services.factory('UsersSearchFactory', function ($resource) {
return $resource('/ngdemo/rest/searchUser', {}, {
search: { method: 'POST', isArray: true, }
})
});
services.factory('CreateUserFactory', function ($resource) {
return $resource('/ngdemo/rest/registerUser', {}, {
create: { method: 'POST' }
})
});
services.factory('UpdateUserFactory', function ($resource) {
return $resource('/ngdemo/rest/updateUser', {}, {
update: { method: 'POST' }
})
});
services.factory('DeleteUserFactory', function ($resource) {
return $resource('/ngdemo/rest/deleteUser', {}, {
delete: { method: 'POST' }
})
});
services.factory('UserFactory', function ($resource) {
return $resource('/ngdemo/rest/findUserById/:id', {}, {
show: { method: 'GET' }
})
});
user-list.html
<div class="container">
<form novalidate="novalidate" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="inputFirstName">First name:</label>
<div class="controls">
<input type="text" id="inputFirstName" ng-model="user.firstName" placeholder="First name"/>
</div>
</div>
<div class="form-group">
<div class="controls">
<a ng-click="searchUser()" class="btn btn-primary btn-xs">Search</a>
</div>
</div>
</form>
</div>
<div class="span6">
<table class="table table-striped table-condensed" >
<thead>
<tr>
<th style="min-width: 80px;"> First Name</th>
<th style="min-width: 80px;"> Last Name</th>
<th style="width:20px;"> </th>
<th style="width:20px;"> </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users" > <!-- | orderBy:sort.sortingOrder:sort.reverse" > -->
<td>{{ user.firstName }}</td>
<td>{{ user.lastName }}</td>
<td><a ng-click="editUser(user.userId)" class="btn btn-small btn-primary">edit</a></td>
<td><a ng-click="deleteUser(user)" class="btn btn-small btn-danger">delete</a></td>
</tr>
</tbody>
</table>
<a ng-click="createNewUser()" class="btn btn-small">create new user</a>
</div>
index.html
<!doctype html>
<html lang="en" ng-app="ngdemo">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ngdemo app</title>
<link rel="stylesheet" href="css/app.css"/>
<link rel="stylesheet" href="css/bootstrap/bootstrap-responsive.min.css"/>
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css"/>
</head>
<body>
<ul class="menu">
<li>user-list</li>
</ul>
<div ng-view></div>
<!-- JQuery ================================================================ -->
<script src="js/jquery/jquery-2.0.3.js"></script>
<!-- Bootstrap ============================================================= -->
<script src="js/bootstrap/bootstrap.js"></script>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="lib/angular/angular-route.js"></script>
<!-- AngularJS App Code ==================================================== -->
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
</body>
</html>
Question:
I am getting the rest call to server and it is sending the response.
When i open index.html it is displaying the out put on the page. When i click on edit(update) or delete buttons or create new user button, the user details are saved in the database but the changed data is not displayed on the table.
This is happened because after editing(updating) , deleting and creating new user the angular code is not waiting for the response from REST call. It immediately calls the $location.path('/user-list'); So old data is displayed in the table.
Please help me.
I have added the success call backs for all the methods update, create, delete as
$scope.createNewUser = function () {
CreateUserFactory.create($scope.user, function(response) {
$location.path('/user-list');
});
}

Resources