I have one factory like this :
app.factory('LoginFactory', [ '$scope', '$http', function($scope, $http) {
var urlBase = "http://localhost:8080/app";
var fact = {};
fact.login = function(userinfo) {
return $http({
method : 'POST',
url : urlBase + '/login',
data : userinfo,
headers : {
'Content-Type' : 'application/json',
'Accept' : 'application/json'
}
});
};
fact.validate = function(sessionId) {
return $http({
method : 'GET',
url : urlBase + '/validate?sessionId=' + sessionId,
});
};
return fact;
} ]);
And Another factory like this :
app.factory('LoginService', [
'Credentials',
function(Credentials, $location, LoginFactory) {
var fact = {};
fact.isLoggedin = function() {
var result = false;
LoginFactory.validate(Credentials.sessionId).success(
function(data, status, headers, config) {
result = true;
}).error(function(data, status, headers, config) {
result = false;
});
return result;
};
fact.authenticate = function(userinfo) {
LoginFactory.login(userinfo).success(
function(data, status, headers, config) {
Credentials = data;
$location.path('/home');
}).error(function(data, status, headers, config) {
$location.path('/login');
});
};
return fact;
} ]);
In the Browser Console I am getting the following error :
Error: LoginFactory is undefined
Can anyone please help me out with this error.
Thanks a lot in advance.
You're declaring your service using the array notation, taking the names of the dependencies to inject followed by the function defining the factory. But you said you only wanted to inject Credentials:
app.factory('LoginService', [
'Credentials',
function(Credentials, $location, LoginFactory) {
So angular only injects Credentials. The above should be replaced by
app.factory('LoginService', [
'Credentials', '$location', 'LoginFactory'
function(Credentials, $location, LoginFactory) {
To avoid those bugs, and the repetition of service names in the array and in the function, I strongly suggest using ngAnnotate in your build.
Related
Although there are many questions regarding the subject , yet I am unable to figure it out , how to proceed further.
I am new in AngularJS. I want to pass data coming from API in Controller and pass it to another function. For this I know I have to create a Service. But after coming to this extend of code I am unable to figure it, how to store it in Service and pass it on other Controller or of function within same Controller. I am new in making Service.
Controller:
$scope.GetR = function (){
$scope.X = null;
$scope.Y = null;
$http({method: 'POST', url: 'http://44.43.3.3/api/infotwo',
headers: {"Content-Type": "application/json"},
data: $scope.ResponseJson
})
.success(function(data, status, headers, config) {
$scope.X = data.X;
$scope.Y = data.Y;
//console.log($scope.X+"and"+$scope.Y);
//Seding RS to API to get AAs
$scope.RJson = {
"ICl": $scope.ICl,
"RS": $scope.X
};
$http({method: 'POST', url: 'http://44.128.44.5/api/apithree',
headers: {"Content-Type": "application/json"},
data: $scope.RJson
})
.success(function(data, status, headers, config) {
$scope.At = data;
$scope.Eq = data.AA.Eq;
$scope.FIn = data.AA.FIn;
$scope.MM = data.AA.MM;
console.log("Eq:"+$scope.Eq+" FIn:"+$scope.FIn+" MM:"+$scope.MM);
}).error(function(data, status, headers, config) {
console.log("API failed...");
});
}).error(function(data, status, headers, config) {
console.log("Something went wrong...");
});
};
Now I want to pass this data to Service so that I can call this output on other API input
.success(function(data, status, headers, config) {
$scope.At = data;
$scope.Eq = data.AA.Eq;
$scope.FIn = data.AA.FIn;
$scope.MM = data.AA.MM;
console.log("Eq:"+$scope.Eq+" FIn:"+$scope.FIn+" MM:"+$scope.MM);
This shows how to create a service and share data between two controllers.
The service:
(function() {
'use strict';
angular
.module('myAppName') // Replace this to your module name
.service('MyService', MyService);
MyService.$inject = [];
function MyService() {
this.data = null;
}
})();
First controller:
(function() {
'use strict';
angular
.module('myAppName') // Replace this to your module name
.controller('MyFirstController', MyFirstController);
MyFirstController.$inject = ['MyService', '$http'];
function MyFirstController(MyService, $http) {
var vm = this;
vm.data = MyService.data;
$http.post('/someUrl', whatEverData).then(resp=> {
MyService.data = resp.data;
})
}
})();
Second controller:
(function() {
'use strict';
angular
.module('myAppName') // Replace this to your module name
.controller('MySecondController', MySecondController);
MySecondController.$inject = ['MyService', '$http'];
function MySecondController(MyService, $http) {
var vm = this;
vm.data = MyService.data; // Here you can use the same data
}
})();
Not sure if this is what you are looking for. Below code is not tested (May have syntax errors)
Service:
function() {
'use strict';
angular
.module('myAppName')
.factory('MyService', MyService);
MyService.$inject = [];
function MyService() {
var data = null;
return {
getData: function() {
return data;
},
setData: function(d) {
data = d;
}
}
}
})();
Controller:
(function() {
'use strict';
angular
.module('myAppName')
.factory('controller', controller);
controller.$inject = ['$scope', '$http', 'MyService'];
function controller($scope, $http, MyService) {
$scope.GetR = function() {
$scope.X = null;
$scope.Y = null;
var promise = $http({
method: 'POST',
url: 'http://44.43.3.3/api/infotwo',
headers: {
"Content-Type": "application/json"
},
data: $scope.ResponseJson
});
promise.success(function(data, status, headers, config) {
$scope.X = data.X;
$scope.Y = data.Y;
//console.log($scope.X+"and"+$scope.Y);
//Seding RS to API to get AAs
$scope.RJson = {
"ICl": $scope.ICl,
"RS": $scope.X
};
}).error(function(data, status, headers, config) {
console.log("Something went wrong...");
});
return promise;
};
$scope.sendRS = function() {
var promise = $http({
method: 'POST',
url: 'http://44.128.44.5/api/apithree',
headers: {
"Content-Type": "application/json"
},
data: $scope.RJson
});
promise.success(function(data, status, headers, config) {
$scope.At = data;
$scope.Eq = data.AA.Eq;
$scope.FIn = data.AA.FIn;
$scope.MM = data.AA.MM;
console.log("Eq:" + $scope.Eq + " FIn:" + $scope.FIn + " MM:" + $scope.MM);
}).error(function(data, status, headers, config) {
console.log("API failed...");
});
return promise;
}
var init = function() {
$scope.GetR().then(function() {
$scope.sendRS().then(function(data) {
MyService.setData({
At: data,
Eq: data.AA.Eq,
FIn: data.AA.FIn,
MM: data.AA.MM
});
})
})
}
init();
}
})();
Other controller
(function() {
'use strict';
angular
.module('myAppName')
.controller('controller1', controller1);
controller1.$inject = ['$scope', 'MyService'];
function controller1($scope, MyService) {
$scope.data = MyService.getData();
}
})();
There is a register form. On submit of register form I am trying to save the data through angular service. It is giving me an error Error: [$http:badreq]
This is my register.controller.js
(function(){
var app = angular.module('myapp');
app.controller('RegisterController',RegisterController);
RegisterController.$inject = ['UserService', '$location','$rootScope'];
function RegisterController(UserService, $location, $rootScope) {
var vm = this;
vm.register = register;
function register(){
UserService.Create(vm.user)
.then(function(response)
{
if(response.success){
}else{
}
});
}
};
})();
Here is the UserService
(function () {
'use strict';
angular
.module('myapp')
.factory('UserService', UserService);
UserService.$inject = ['$timeout', '$filter', '$q', '$http'];
function UserService($timeout, $filter, $q, $http) {
var service = {};
service.Create = Create;
return service;
var url='ajax.php';
function Create(user) {
$http({
method: 'post',
url: url,
data: user,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).
success(function(data, status, headers, config) {
console.log(data);
}).
error(function(data, status, headers, config) {
console.log(data);
});
}
}
})();
What is the issue with code. Please help. Thanks in advance
You are using return service; prior to define the URL so the $http service get's undefined instead of URL. Solution is to move return statement in the last of the service function like:
(function () {
'use strict';
angular
.module('myapp')
.factory('UserService', UserService);
UserService.$inject = ['$timeout', '$filter', '$q', '$http'];
function UserService($timeout, $filter, $q, $http) {
var service = {};
service.Create = Create;
var url='ajax.php';
function Create(user) {
$http({
method: 'post',
url: url,
data: user,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).
success(function(data, status, headers, config) {
console.log(data);
}).
error(function(data, status, headers, config) {
console.log(data);
});
}
return service;
}
})();
I am trying to get the model data in angular js ,but not able to get it . I printed the value on spring mvc side .The data is getting stored and is retrieved successfully with the given key.Can anyone tell me how can I achieve this .
My controller-
#RequestMapping(value = "/home.web", method = RequestMethod.GET, produces = {
"application/json" })
public ModelAndView getUSCity(#RequestParam ("statechoice") String statechoice) {
List<String> msa = new ArrayList<String>();
msa = msaService.getMsaCodes(statechoice);
/*ModelAndView model = new ModelAndView("Home");
model.addObject("cities",msa);
System.out.println(model.getModel().get("cities"));*/
//return msa;
return new ModelAndView("Home", "cities",msa);
}
My angular js -
function MyController($scope, $http) {
$scope.getPersonData = function() {
$http({
method : 'GET',
url : 'home.web'
}).success(function(data, status, headers, config) {
alert(data);
$scope.cities = data;
}).error(function(data, status, headers, config) {
console.log("error");
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
};
Split your code into controller and service because you should not do api calls from cotroller directly(best case). Services should be used. Controllers are only be used to controlling model to show it in the view.
myService.js
app.service('myService', ['$http', '$q', function($http, $q){
return {
getPersons: function(obj) {
var deferred = $q.defer();
$http({
method : obj.method,
url : obj.url
}).then(function(response) {
deferred.resolve(response);
}, function(error) {
alert(error);
deferred.reject(error);
// called asynchronously if an error occurs
// or server returns response with an error status.
});
return deferred.promise();
};
}
});
myController.js
function MyController('MyController', ['$scope', 'myService', function($scope, myService){
$scope.persons = [];
var obj = {method: 'GET', url: 'home.web'};
myService.getPersons(obj).then(function(response){
$scope.persons = response.data // or $scope.persons = response check yourself
}, function(error){
alert(error);
})
}]);
I'm trying to write an Angular service and it seems like there is something missing. My problem is its not returning any value to my Angular controller
getPrepTimes() method is not returning the http data
But when I check the network (via Chrome dev tools) it will correctly call the external api and return a json object as a response
#my service
'use strict';
angular.module('recipeapp')
.service('prepTimeService',['$http', function($http){
this.prepTime = getPrepTimes();
function getPrepTimes(){
$http({
url: '/prep_times/index.json',
method: 'GET'
})
.success(function (data, status, header, config){
return data;
});
};
}
]);
#controller
'use strict';
angular.module('recipeapp')
.controller('recipeCtrl', ['$scope', 'prepTimeService', function($scope, prepTimeService){
$scope.prep_time = prepTimeService.prepTime;
}]);
When I checked the method getPrepTimes() with returning a string it works. What could be missing here?
A couple things are wrong with the above. You assign this.prepTime to getPrepTimes(). The () there will invoke getPrepTimes immediately, and not when you actually call it! You also need to utilize callbacks to get your data back and use it:
angular.module('recipeapp').service('prepTimeService',['$http', function($http){
this.prepTime = getPrepTimes;
function getPrepTimes(callback) {
$http({
url: '/prep_times/index.json',
method: 'GET'
}).success(function (data, status, header, config){
callback(data);
});
};
}]);
And now use it like so:
prepTimeService.prepTime(function(data) {
$scope.prep_time = data;
});
Calls to the $http service are async, which means you need to return a promise (and not a value):
this.prepTime = function() {
return $http({
url: '/prep_times/index.json',
method: 'GET'
});
};
And on the controller:
angular.module('recipeapp')
.controller('recipeCtrl', ['$scope', 'prepTimeService', function($scope, prepTimeService){
$scope.prep_time = prepTimeService.prepTime()
.success(function (data, status, header, config){
$scope.someVar = data;
});
}]);
Wrap answer with promise:
var self = this;
var deferred = $q.defer();
self.getPrepTimes = function() {
$http({
url: '/prep_times/index.json',
method: 'GET'
})
.success(function(data, status, headers, config) {
if (data.error === undefined) {
deferred.resolve(data);
} else {
if (data.error !== undefined) {
} else {
deferred.reject(data);
}
}
}).error(function(data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
};
In controller call it:
prepTimeService.getPrepTimes().then(function(result) {
$scope.prep_time = result;
},
function(error) {
// show alert
});
I've having a problem to get the resolve mechanism working in my application.
I separated the webservice call into an extra module and using deferred/promise to have callbacks.
Before showing the state "workflowdefinitions.detail", the app should load the workflow definition be using the workflowDefinitionId of the $stateParams and call the function "getWorkflowDefinition" of the workflowDefinitionService at the service module.
I tried out multiple things that I had read here, but can't get it working. How do I need to handle the returned promise to pass the return data to the workflowDefinition defined by resolve?
Can this work with my services or do I have to define the service in a different way?
app.js
var atpApp = angular.module('atpApp', [ 'ui.router', 'workflowServices', 'workflowControllers' ]);
atpApp.config([ '$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider , $locationProvider) {
$urlRouterProvider.otherwise('/workflowdefinitions');
$stateProvider.state('workflowdefinitions', {
url : '/workflowdefinitions',
controller : 'WorkflowDefinitionListCtrl',
templateUrl : 'partials/workflowdefinition-list.html'
})
.state('workflowdefinitions.detail', {
url : '/:workflowDefinitionId',
views : {
'#' : {
templateUrl : 'partials/workflowdefinition-detail.html',
controller : 'WorkflowDefinitionDetailCtrl',
resolve: {
workflowDefinition: function($stateParams, workflowDefinitionService) {
return workflowDefinitionService.getWorkflowDefinition($stateParams.workflowDefinitionId);
}
}
}
}
});
} ]);
atpApp.run([ '$rootScope', '$state', '$stateParams', function($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
} ]);
Module for Services (workflowSevices.js)
var workflowServices = angular.module('workflowServices', []);
workflowServices.service('workflowDefinitionService', function($http, $q) {
var config = {headers: {
'Accept': 'application/json'
}
};
this.getWorkflowDefinitions = function(){
var deferred = $q.defer();
$http.get('http://localhost:8080/vms-atp-webapp/services/rest/workflows', config).
success(function(data, status) {
deferred.resolve(data);
}).error(function(data, status) {
deferred.reject(data);
});
return deferred.promise;
};
this.getWorkflowDefinition = function(workflowDefinitionId){
var deferred = $q.defer();
$http.get('http://localhost:8080/vms-atp-webapp/services/rest/workflows/'+workflowDefinitionId, config).
success(function(data, status) {
deferred.resolve(data);
}).error(function(data, status) {
deferred.reject(data);
});
return deferred.promise;
};
this.activateWorkflowDefinition = function(workflowDefinitionId){
var deferred = $q.defer();
$http.post('http://localhost:8080/vms-atp-webapp/services/rest/workflows/'+workflowDefinitionId+"/activate", config).
success(function(data, status) {
deferred.resolve(data);
}).error(function(data, status) {
deferred.reject(data);
});
return deferred.promise;
};
this.deactivateWorkflowDefinition = function(workflowDefinitionId){
var deferred = $q.defer();
$http.post('http://localhost:8080/vms-atp-webapp/services/rest/workflows/'+workflowDefinitionId+"/suspend", config).
success(function(data, status) {
deferred.resolve(data);
}).error(function(data, status) {
deferred.reject(data);
});
return deferred.promise;
};
});
This concept should be working. There is a plunker, which should be doing almost the same you've tried above. No changes, as is. (as is in the code above)
The only change - for example purposes - is the service method getWorkflowDefinition, which does delay because of $timeout service, but then returns the param passed
this.getWorkflowDefinition = function(param){
var deferred = $q.defer();
$timeout(function(){
deferred.resolve(param);
}, 750)
return deferred.promise;
};
So, your concept, design is working, check more here: plunker
Additionally you don't need the boiler plate for deferred/resolve everywhere.
This code
var deferred = $q.defer();
$http.post( 'http://localhost:8080/vms-atp-webapp/services/rest/workflows/' + workflowDefinitionId +"/suspend", config).
success(function(data, status) {
deferred.resolve(data);
}).error(function(data, status) {
deferred.reject(data);
});
return deferred.promise;
can be simplified to
simple
return $http.get('http://localhost:8080/vms-atp-webapp/services/rest/workflows', config);
This is because the $http.get returns a promise which when fulfilled is internally resolved/rejected on success and error.