Spring MVC not being called by the Angular JS controller - javascript

I'm trying to intgrate Angular JS with an existing Spring MVC project.
I had à problem calling a Spring controller from the Angular JS controller.
This is my app.js:
'use strict';
var AdminApp = angular.module('AdminApp',[]);
And the service:
'use strict';
AdminApp.factory('AdminService', ['$http', '$q', function($http, $q) {
return {
fetchAllTerminals: function() {
return $http.get('http://localhost:8081/crmCTI/admin/terminal')
.success(function(response) {
console.log('Service');
return response.data;
})
.error(function(errResponse) {
console.error('Error while fetching terminals');
return $q.reject(errResponse);
});
}
};
}]);
and the controller:
'use strict';
AdminApp.controller('AdminController', ['$scope', 'AdminService', function($scope, AdminService) {
var self = this;
self.terminal={id:'',connectedUser:'',type:'',state:''};
self.terminals=[];
self.fetchAllTerminals = function() {
console.log('Controller');
AdminService.fetchAllTerminals()
.success(function() {
self.terminals = d;
})
.error(function() {
console.error('Error while fetching Terminals');
});
};
self.reset = function() {
self.terminal = {id : null, connectedUser : '', type : '', state : ''};
};
}]);
The JSP I'm using to display the data is:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head></head>
<body ng-app="AdminApp" ng-init="names=['Jani','Hege','Kai']">
<div ng-controller="AdminController as adminController">
<table>
<thead>
<tr>
<th>Id</th>
<th>Login</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="terminal in adminController.terminals">
<td>{{terminal.id}}</td>
<td>{{terminal.connectedUser}}</td>
<td>{{terminal.type}}</td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript" src="${pageContext.request.contextPath}/vendors/angular/1.4.4/angular.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/app.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/controller/admin-controller.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/service/admin-service.js"></script>
</body>
</html>
I can access my Spring Controller from a web browser and it returns some data but it's not being called by the Angular JS controller
Am I missing something here?
Could you please help me?
Thank you

To return a data from your service function you should use .then function which has ability to return a data when promise gets resolved OR reject. That you can't to with .success & .error function.
.success & .error method of $http has been **deprecated
Factory
AdminApp.factory('AdminService', ['$http', '$q', function($http, $q) {
return {
fetchAllTerminals: function() {
return $http.get('http://localhost:8081/crmCTI/admin/terminal')
.then(function(response) {
console.log('Service');
return response.data;
},function(errResponse) {
console.error('Error while fetching terminals');
return $q.reject(errResponse);
});
}
};
}]);
Then controller method will again place .then function on the factory method. So the 1st function of .then will get called on resolved of fetchAllTerminals call, if it gets rejected 2nd function will get called.
Controller
self.fetchAllTerminals = function() {
console.log('Controller');
AdminService.fetchAllTerminals()
.then(function(data) {
self.terminals = data;
}, function(error) {
console.error('Error while fetching Terminals');
});
};

try this:
'use strict';
angular.module('AdminApp',[]);
And the service:
'use strict';
angular.module('AdminApp').factory('AdminService', ['$http', '$q', function($http, $q) {
return {
fetchAllTerminals: function() {
return $http.get('http://localhost:8081/crmCTI/admin/terminal')
.success(function(response) {
console.log('Service');
return response.data;
})
.error(function(errResponse) {
console.error('Error while fetching terminals');
return $q.reject(errResponse);
});
}
};
}]);
controller:
'use strict';
angular.module('AdminApp').controller('AdminController', ['$scope', 'AdminService', function($scope, AdminService) {
var self = this;
self.terminal={id:'',connectedUser:'',type:'',state:''};
self.terminals=[];
self.fetchAllTerminals = function() {
console.log('Controller');
AdminService.fetchAllTerminals()
.success(function() {
self.terminals = d;
})
.error(function() {
console.error('Error while fetching Terminals');
});
};
self.reset = function() {
self.terminal = {id : null, connectedUser : '', type : '', state : ''};
};
}]);

Related

AngularJS - Dynamic parameter in $http URL

The URL I use to retreive a JSON for my app has a dynamic parameter (:id ). I'm not too sure how I can work with this, so that it passes the ID the user has chosen. Just need a bit of guidance.
app.factory('bookcategories', ['$http', function($http) {
return $http.get('http://52.41.65.211:8028/api/v1/categories/:id/books.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
Controller
app.controller('BookCategoryController', ['$scope', 'categories', '$routeParams', function($scope, categories, $routeParams) {
categories.success(function(data) {
$scope.detail = data.categories[$routeParams.bookId];
$scope.currentCategoryIndex = parseInt($routeParams.categoryId);
$scope.myCategoriesDetails = $scope.category;
});
}]);
app.js
...
.when('/categories/:categoryId', {
controller: 'BookCategoryController',
templateUrl: 'views/booksincategory.html'
})
...
HTML
<h3 class="title">{{book.title}}</h3>
You could achieve this with a little service like the following code example. A factory is a wrong choice here.
app.service('bookCategories', ['$http', function($http) {
this.get = function (id) {
return $http.get('http://52.41.65.211:8028/api/v1/categories/'+ id + '/books.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
};
}]);
And than use it like:
app.controller('MyCtrl', function(bookCategories) {
bookCategories.get(1).then(function (result) {
console.log(result);
});
});

Angular module adding a Service injection error

First time doing an angular application, combining different tutorials but this is the first time I am trying to inject a service.
I have one of my View's controllers like:
angular.module("myApp.Pages").controller('signupController', ['$scope', '$location', '$timeout', 'authService', function ($scope, $location, $timeout, authService) {
}
however am seeing an error when I look at the Console in Developer Tools:
angular.js:12793 Error: [$injector:unpr] Unknown provider:
authServiceProvider <- authService <- signupController
http://errors.angularjs.org/1.5.0-beta.2/$injector/unpr?p0=authServiceProvider%20%3C-%20authService%20%3C-ignupController
My project structure is:
-Client
-App
-Components
-Services
-authService.js
-myAppCore.js
-Views
-app.js
-appRouting.js
-Scripts (References)
-Theme (Css)
-Index.html
My index.html scripts I add:
<!-- Angular References-->
<script src="References/Angular/angular.js"></script>
<script src="References/Angular/angular-route.js"></script>
<script src="References/Angular/angular-ui-router.min.js"></script>
<!-- End Angular References-->
<!-- my app and dependent modules -->
<script src="App/app.js"></script>
<script src="App/appRouting.js"></script>
<!-- Services -->
<script src="App/Components/Services/authService.js"></script>
<!-- END services-->
<!-- Controllers for your pages-->
<script src="App/Pages/Home/homeController.js"></script>
<script src="App/Pages/ContactUs/contactusController.js"></script>
<script src="App/Pages/Entry/entryController.js"></script>
<script src="App/Pages/Signup/signupController.js"></script>
<!-- End Controllers for the page-->
My app.js
angular.module("myApp", [
// User defined modules
'myApp.Templates', // templates
'myApp.Pages', // Pages
'myApp.Core', // Core
// Angular modules
'ui.router', // state routing
'ngRoute', // angular routing
'angular-loading-bar', //loading bar
'LocalStorageModule', //local browser storage
])
and appRouting.js
angular.module("myApp")
.config(["$stateProvider", function ($stateProvider) {
$stateProvider.state('Home', {
url: '/Home',
templateUrl: 'App/Pages/Home/home.html',
controller: 'homeController'
})
.state('Entry', {
url: '/Entry',
templateUrl: 'App/Pages/Entry/entry.html',
controller: 'entryController'
})
.state('Signup', {
url: '/Signup',
templateUrl: 'App/Pages/Signup/signup.html',
controller: 'signupController'
})
.state('Contactus', {
url: '/Contactus',
templateUrl: 'App/Pages/ContactUs/contactus.html',
controller: 'contactusController'
})
.state("otherwise", {
url: "*path",
templateUrl: "App/Pages/NotFound/notFound.html"
});
}])
.run(["$location", function ($location) {
// Go to state dashboard
$location.url('/Home');
}]);
authService which handles login/register:
app.factory('authService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService) {
var serviceBase = '<location>';
var authServiceFactory = {};
var _authentication = {
isAuth: false,
userName: ""
};
var _saveRegistration = function (registration) {
_logOut();
return $http.post(serviceBase + 'api/account/register', registration).then(function (response) {
return response;
});
};
var _login = function (loginData) {
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;
var deferred = $q.defer();
$http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {
localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName });
_authentication.isAuth = true;
_authentication.userName = loginData.userName;
deferred.resolve(response);
}).error(function (err, status) {
_logOut();
deferred.reject(err);
});
return deferred.promise;
};
var _logOut = function () {
localStorageService.remove('authorizationData');
_authentication.isAuth = false;
_authentication.userName = "";
};
var _fillAuthData = function () {
var authData = localStorageService.get('authorizationData');
if (authData) {
_authentication.isAuth = true;
_authentication.userName = authData.userName;
}
}
authServiceFactory.saveRegistration = _saveRegistration;
authServiceFactory.login = _login;
authServiceFactory.logOut = _logOut;
authServiceFactory.fillAuthData = _fillAuthData;
authServiceFactory.authentication = _authentication;
return authServiceFactory;
}]);
myAppPages.js and myAppCore.js are the same just their respective names :
angular.module("myApp.Pages", []);
Edit: Seeing a "app is not defined" reference error in authService
You don't defined var app, so use angular.module("myApp") to define your factory
angular.module("myApp").factory('authService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService)
Also you can declare var app = angular.module("myApp") and use app
I simply did not declare:
var app = angular.module(...)
And my service was referencing app when that did not exist.

Exchanging data between different controllers in angularjs?

I am trying to exchange data between two different controllers. I will access data in different controllers. I use /loading for showing a spinner. While navigating between different pages I load this spinner and after some time delay I navigate to another url which is intended. So I use this service to store the uri.
I have the following service in my angular js app.
myApp.service('myService', function() {
var data = "";
return {
getUri: function () {
return data;
},
setUri: function (uri) {
data = uri;
}
};
});
The following are my routes:
twitter.config([ '$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider, $routeParams) {
$routeProvider.when('/', {
templateUrl : 'main.html',
controller : 'mainController'
}).when('/loading', {
templateUrl : 'spinner.html',
controller : 'spinnerController'
}).when('/login', {
templateUrl : 'login.html',
controller : 'loginController'
}).when('/signup', {
templateUrl : 'signup.html',
controller : 'signupController'
});
$locationProvider.html5Mode(true);
} ]);
so I am trying to put data into the service by doing
myService.set('mydata');
and getting data by
myService.get();
But every time when I try to access the service in different controllers defined above I get empty string.
your service public methods are getUri and setUri but you are trying to use as myservice.get() and myservic.set().check the below snippet
var myApp = angular.module('myApp', []);
myApp.controller('controller1', function($scope, myService) {
$scope.ControllerData = 'From Controller 1';
myService.setUri('www.google.com');
});
myApp.controller('controller2', function($scope, myService) {
$scope.ControllerData = 'From Controller 2';
$scope.sharedData = myService.getUri();
});
myApp.service('myService', function() {
var data = "";
return {
getUri: function() {
return data;
},
setUri: function(uri) {
data = uri;
}
};
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<meta charset=utf-8 />
<title>ng-click</title>
</head>
<body>
<div ng-controller="controller1">
Controller1 Data: {{ControllerData}}
</div>
<div ng-controller="controller2">
Controller 2 Data:{{ControllerData}}
<br>Shared Data :{{sharedData}}
</div>
</body>
</html>
Try to set in this way :
setUri: function (uri) {
this.data = uri;
}

error when injecting service in controller

I am trying to consume Web API using AngularJs but getting struck angular side which is hard for me to figure out.
I created HTML, controller and service. Everything seems ok to me but when running the app i get the injection error.
html
<html >
<head>
<title>Motors </title>
<script src="/Scripts/angular.js"></script>
<script src="/Scripts/angular-route.js"></script>
<script src="/View/motorController.js"></script>
</head>
<body ng-app="myApp" ng-controller="motorController">
<div>
<table class="table">
<tr>
<th>Id</th>
<th>Name</th>
<th>Country</th>
</tr>
<tr ng-repeat="m in motors">
<td>{{m.Id}}</td>
<td>{{m.Name}}</td>
<td>{{m.Country}}</td>
</tr>
</table>
</div>
</body>
</html>
AngularJs controller
var module = angular.module('myApp', [])
.controller('motorController', ['$scope', '$motorService',function ($scope, motorService) {
getMotors();
function getMotors() {
motorService.GetAllMotors()
.success(function (motors) {
$scope.motors = motors;
})
.error(function (error) {
$scope.status = 'Unable to load motor data: ' + error.message;
});
}
}]);
angular service
motorApp.factory('motorService', function ($http) {
var urlBase = 'http://localhost:40738/api';
var motorService = {};
motorService.GetAllMotors = function () {
return $http.get(urlBase + '/GetAllMotors');
};
return motorService;
});
Error i am getting on chrmoe browser console
Error: [$injector:unpr] Unknown provider: $motorServiceProvider <- $motorService <- motorController
You have a extra $ infront of MotorService, change
From:
.controller('motorController', ['$scope', '$motorService',function ($scope, motorService)
To:
.controller('motorController', ['$scope', 'motorService',function ($scope, motorService)
The problem with your code is that the factory is given a different module name "motorApp" instead of module name "module".
Use
module.factory('motorService', function ($http) { //change here
var urlBase = 'http://localhost:40738/api';
var motorService = {};
motorService.GetAllMotors = function () {
return $http.get(urlBase + '/GetAllMotors');
};
return motorService;
});
Also in your controller you should remove the "$" from injected service name "motorService"
var module = angular.module('myApp', [])
.controller('motorController', ['$scope', 'motorService',function ($scope, motorService) {
getMotors();
function getMotors() {
motorService.GetAllMotors()
.success(function (motors) {
$scope.motors = motors;
})
.error(function (error) {
$scope.status = 'Unable to load motor data: ' + error.message;
});
}
}]);

Firebase API issue with AngularJS website example project

Beginning to dive into AngularJS so I went to their website, but got stuck on the wire up a backend portion where Angular uses Firebase. The first issue came from the ordering of dependencies:
angular.module('project', ['ngRoute', 'firebase'])
changed to
angular.module('project', ['firebase', 'ngRoute'])
But now it's telling my that $add, in my $scope.save call, is undefined.
Similar $add undefined questions are here and here, but neither seem to apply.
Note: I'm running node's http-server, so I'm assuming it's not a localhost problem.
Scripts
angular.module('project', ['firebase', 'ngRoute'])
.value('fbURL', 'https://unique-url-yay.firebaseio.com/')
.service('fbRef', function(fbURL) {
return new Firebase(fbURL)
})
.service('fbAuth', function($q, $firebase, $firebaseAuth, fbRef) {
var auth;
return function () {
if (auth) return $q.when(auth);
var authObj = $firebaseAuth(fbRef);
if (authObj.$getAuth()) {
return $q.when(auth = authObj.$getAuth());
}
var deferred = $q.defer();
authObj.$authAnonymously().then(function(authData) {
auth = authData;
deferred.resolve(authData);
});
return deferred.promise;
}
})
.service('Projects', function($q, $firebase, fbRef, fbAuth) {
var self = this;
this.fetch = function () {
if (this.projects) return $q.when(this.projects);
return fbAuth().then(function(auth) {
var deferred = $q.defer();
var ref = fbRef.child('projects/' + auth.auth.uid);
var $projects = $firebase(ref);
ref.on('value', function(snapshot) {
if (snapshot.val() === null) {
$projects.$set(window.projectsArray);
}
self.projects = $projects.$asArray();
deferred.resolve(self.projects);
});
return deferred.promise;
});
};
})
.config(function($routeProvider) {
$routeProvider
.when('/', {
controller:'ListCtrl',
templateUrl:'list.html',
resolve: {
projects: function (Projects) {
return Projects.fetch();
}
}
})
.when('/edit/:projectId', {
controller:'EditCtrl',
templateUrl:'detail.html'
})
.when('/new', {
controller:'CreateCtrl',
templateUrl:'detail.html'
})
.otherwise({
redirectTo:'/'
});
})
.controller('ListCtrl', function($scope, projects) {
$scope.projects = projects;
})
.controller('CreateCtrl', function($scope, $location, Projects) {
$scope.save = function() {
Projects.projects.$add($scope.project).then(function(data) {
$location.path('/');
});
};
})
.controller('EditCtrl',
function($scope, $location, $routeParams, Projects) {
var projectId = $routeParams.projectId,
projectIndex;
$scope.projects = Projects.projects;
projectIndex = $scope.projects.$indexFor(projectId);
$scope.project = $scope.projects[projectIndex];
$scope.destroy = function() {
$scope.projects.$remove($scope.project).then(function(data) {
$location.path('/');
});
};
$scope.save = function() {
$scope.projects.$save($scope.project).then(function(data) {
$location.path('/');
});
};
});
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Angular</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-resource.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js">
</script>
<script src="https://cdn.firebase.com/js/client/2.0.4/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/0.9.0/angularfire.min.js"></script>
<script src="scripts.js" type="text/javascript"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body style="padding:20px;">
<div ng-app="project" class="ng-scope"></div>
<div ng-view></div>
</body>
</html>
Alright, a few things are going on here:
Suggestions
AngularFire was updated to 1.1.1 and $firebase is now deprecated. Use $firebaseObject and $firebaseArray instead.
There is no need to do all that stuff in your Projects service and return a promise. $firebaseObject and $firebaseArray return promises.
Example
Check out this PLNKR I made showing a working version of what you're trying to accomplish.
It's tied to one of my public Firebase instances.
You can create a new piece of data and see it on the home page.
JavaScript:
(function(angular) {
angular.module('project', ['firebase', 'ngRoute'])
.value('fbURL', 'https://sb-plnkr.firebaseio.com/so:28942661')
.service('fbRef', function(fbURL) {
return new Firebase(fbURL)
})
.service('fbAuth', function($q, $firebaseAuth, fbRef) {
var auth;
return function () {
if (auth) return $q.when(auth);
var authObj = $firebaseAuth(fbRef);
if (authObj.$getAuth()) {
return $q.when(auth = authObj.$getAuth());
}
var deferred = $q.defer();
authObj.$authAnonymously().then(function(authData) {
auth = authData;
deferred.resolve(authData);
});
return deferred.promise;
}
})
.service('Projects', function($q, $firebaseArray, fbRef) {
this.sync = $firebaseArray(fbRef);
this.sync.$loaded().then(function(data) {
var projects = data;
});
return this.sync;
})
.controller('ListCtrl', function($scope, $location, Projects) {
Projects.$loaded().then(function(data){
$scope.projects = data;
});
})
.controller('CreateCtrl', function($scope, $location, Projects) {
console.log("CreateCtrl");
$scope.save = function() {
console.debug("Adding");
if ($scope.project && $scope.project.content !== '') {
Projects.$add($scope.project).then(function(ref) {
console.log("Added ref",ref);
$location.path('/');
}).catch(function(errorObject){
console.error(errorObject);
});
} else {
alert("You have to enter something.");
}
};
})
.controller('EditCtrl',function($scope, $location, $routeParams, Projects) {
var projectId = $routeParams.projectId,
projectIndex;
$scope.init = function(){
Projects.$loaded().then(function(data) {
$scope.projects = data;
console.info("EditCtrl - Projects.$loaded():",data);
projectIndex = $scope.projects.$indexFor(projectId);
$scope.project = $scope.projects[projectIndex];
});
}
$scope.destroy = function() {
$scope.projects.$remove($scope.project).then(function(data) {
$location.path('/');
});
};
$scope.save = function() {
$scope.projects.$save($scope.project).then(function(data) {
$location.path('/');
});
};
})
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
controller:'ListCtrl',
templateUrl:'list.html'
})
.when('/edit/:projectId', {
controller:'EditCtrl',
templateUrl:'detail.html'
})
.when('/new', {
controller:'CreateCtrl',
templateUrl:'create.html'
})
.otherwise({
redirectTo:'/'
});
$locationProvider.html5Mode(true);
});
})(window.angular);
HTML:
(index.html)
<body style="padding:20px;">
<div ng-app="project" ng-controller="EditCtrl">
New
<div ng-view></div>
</div>
</body>
(create.html)
<h2>Create</h2>
<button ng-click="save()">Save</button>
(list.html)
<h2>List</h2>
<div ng-repeat="(key,data) in projects">
<span>$scope.projects[<span ng-bind="key"></span>].content : </span>
<span ng-bind="data.content"></span>
</div>
<h2>Object Debug</h2>
<pre ng-bind="projects | json"></pre>
Hope that helps!

Categories

Resources