Angular async http request - javascript

I am trying to do a http ququest in angular. Somehow it seems am missing out on something which i cannot figure out what it is?
On Page load i get this error:
Error: [$injector:undef] http://errors.angularjs.org/1.4.5/$injector/undef?p0=%24formServices
My Service:
app.factory('$formServices',['$http','$q',function ($http, $q) {
function postSubmit (fData) {
return $http({
url: 'forms/Form1.php',
method: "POST",
data: { items: JSON.stringify(fData) }
});
}
}
]
);
And the controller that calls the service:
$formServices.postSubmit($scope.Parameters).then(function (response) {
console.log(response);
$scope.Results = response;
});
What am i missing out on?

$injector:undef
Try adding a return to your factory. Also, if you wish to call the function with dot notation you need to place the function inside of an object.
app.factory('$formServices',['$http','$q',function ($http, $q) {
return {
postSubmit: function(fData) {
return $http({
url: 'forms/Form1.php',
method: "POST",
data: { items: JSON.stringify(fData) }
});
}
}
}
]
);

Factory must return object from factory, so that will be exposed via to factory consumer via injecting its dependency.
Code
app.factory('$formServices', ['$http', '$q', function($http, $q) {
function postSubmit(fData) {
return $http({
url: 'forms/Form1.php',
method: "POST",
data: {
items: JSON.stringify(fData)
}
});
}
// should object
return {
postSubmit: postSubmit //link post submit to function
}
}]);

The issue is that your factory does not return an object. To learn more about this I suggest reading https://docs.angularjs.org/guide/providers
Evilzebra's answer would work I believe, but if you ever wanted to have more functionality in your factory, a good way to structure factories is:
app.factory('$formServices',['$http','$q',function ($http, $q) {
var service = {};
service.postSubmit = function (fData) {
return $http({
url: 'forms/Form1.php',
method: "POST",
data: { items: JSON.stringify(fData) }
});
}
return service;
}]);
This would allow you to add more features, appending them to the service object.

Related

How to call php file via factory/service method using Angular.js

I need to call php file using service/Factory method using Angular.js. Here instead of calling $http repeatedly in each file to call diferent php file for different purpose, I need to make it common. I am explaining one example below.
logincontroller.js:
var loginAdmin=angular.module('Takeme');
loginAdmin.controller('loginController',function($scope,$http,$location,$window,inputField){
$http({
method: 'POST',
url: "php/Login/verify.php",
data: userData,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
},function errorCallback(response) {
});
}
I have one common route.js file which is common for all controller and given below.
route.js:
var Admin=angular.module('Takeme',['ui.router', '720kb.datepicker','ngMessages','ngCapsLock','ui.bootstrap','ngFileUpload','angularUtils.directives.dirPagination']);
Admin.run(function($rootScope, $state) {
$rootScope.$state = $state;
});
Admin.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/',{
url: '/',
templateUrl: 'view/login.html',
controller: 'loginController'
})
})
Admin.factory('inputField',function($timeout,$window){
return{
borderColor:function(id){
$timeout(function() {
var element = $window.document.getElementById(id);
if(element){
element.focus();
element.style.borderColor = "red";
}
});
},
clearBorderColor:function(id){
$timeout(function() {
var element = $window.document.getElementById(id);
if(element){
element.style.borderColor = "#cccccc";
}
});
}
};
});
Here I need to that $http service to call the php file common for which in every controller I will call that $http repeatedly. I need to pass only the parameters for $http service and return the response.
create a factory/service
angular.module('myApp').factory('DataService', DataService);
DataService.$inject = ['$http', '$q'];
function DataService($http, $q) {
return {
getData: getData,
}
function getData(userData) {
var deferred = $q.defer();
$http({
method: 'POST',
url: "php/Login/verify.php",
data: userData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
deferred.resolve(response.data);
},
function(error) {
deferred.reject(error.data);
});
return deferred.promise;
};
}
then use this factory whenever you need in a controller
angular.module('myApp')
.controller('MyController', ['$scope', 'DataService',
function($scope, DataService ) {
$scope.getMyData = function() {
var data = {};
DataService.getData(data)
.then(function(response) {
}, function(error) {
});
};
}
]);

how to get the data before loading the page in angularjs providers

I have a requirement like to get the data before loading the page by using angular js providers ,am not implement it please anybody help me.
This is my code please go through it
hiregridApp.provider('organizationService', function() {
return {
getOrganization: ['$http', '$location',
function($http, $location) {
$http({
method: 'GET',
url: http: //dev.api.hiregrid.io/api/customer/token/hiregrid',
}).success(function(data) {
$log.log(data);
}).error(function(error, status) {
$routeParams.code = status;
$location.path('/error/' + $routeParams.code);
});
}
]
}, this.$get: ['$http', '$location',
function($http, $location) {
var obj = '';
alert("hai");
obj.getOrganization = function() {
$http({
method: 'GET',
url: 'http://dev.api.hiregrid.io/csbuilder- api/api/csbuilder/hiregrid',
}).success(function(data) {
$log.log(data);
}).error(function(error, status) {
$routeParams.code = status;
$location.path('/error/' + $routeParams.code);
});
return obj;
}
}
];
});
hiregridApp.config(function(organizationServiceProvider) {
console.log(organizationServiceProvider);
organizationServiceProvider.getOrganization("http://dev.api.hiregrid.io");
});
You could resolve your data in routing so when ever you navigate to a page it will resolve your data and then navigate.
Note if server take long time to response so it will not navigate u till it has resolved your promise.
You can use your provider in config where you have your router configuration.
angular.module ('app',[]).config (function(yourProvider){})
var config = { headers : {'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8;'}};
App.provider('organizationService', ['$http',
function($http) {
return {
getOrganization: function (){
$http.get("http: //dev.api.hiregrid.io/api/customer/token/hiregrid",config)
.success(function(data) {
$log.log(data);
}).error(function(error, status) {
$routeParams.code = status;
$location.path('/error/' + $routeParams.code);
});
}
}
}
]);
If you want to load data before page loaded, use resolve inside your router. For that you don't need providers.
About resolve you can read here angular router

How to make View redirects in AngularJS without constant server requests

Everytime when I make View redirect (I use href to do so) I can see that AngularJS runs GetAjaxData1, GetAjaxData2.
In the other words: instead of the single initial request to the server, I do it everytime when I make View redirection. What is wrong?
Here is my AngularJS code:
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {
controller: 'UController',
templateUrl: '/Partial/View1.html'
}).when('/View2', {
controller: 'UController',
templateUrl: '/Partial/View2.html'
}).otherwise({redirectTo: '/View3'});
}]).factory('uFactory', function () {
var factory = {};
data1 = [];
data2 = [];
factory.getAjaxData1 = function () {
$.ajax({
url: url,
type: 'GET',
contentType: "application/json",
async: false,
success: function (result) {
data1 = result;
}
});
return data1;
};
factory.getAjaxData2 = function () {
$.ajax({
url: url,
type: 'GET',
contentType: "application/json",
async: false,
success: function (result) {
data2 = result;
}
});
return data2;
}
};
var controllers = {};
controllers.uController = function ($scope, $location, uFactory) {
$scope.data1 = uFactory.getAjaxData1();
$scope.data2 = uFactory.getAjaxData2();
};
You definitely have to read about $http and ng-resource library and
try more angular way in your application and you also should
understand that ajax request is always asynchronous, and try to
understand promise pattern.
Technically - what you need is a caching - no matter how you are going to implement this - you need to make a single call to the API and the to cache variable.
I don't like idea of usage $.ajax, but it can look like this:
angular.module('myApp').config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {
controller: 'UController',
templateUrl: '/Partial/View1.html'
}).when('/View2', {
controller: 'UController',
templateUrl: '/Partial/View2.html'
}).otherwise({redirectTo: '/View3'});
}]).factory('uFactory', function () {
return {
getFirstPromise: function () {
if (!this.$$firstPromise) {
this.$$firstPromise = $.ajax({
url: url,
type: 'GET',
contentType: "application/json"
}).then(function (data) {
window.data1 = data;
});
}
return this.$$firstPromise;
}
... //some other code
}
});
var controllers = {
uController: function ($scope, $location, uFactory) {
uFactory.getFirstPromise().then(function (data) {
$scope.data1 = data;
});
// same for other data - and don't try to make ajax requests synhronous ;-)
}
};
Controllers are not singletons. So your "UController" is created everytime your view changes. I assume that the factory is used inside this controller. See: What is the lifecycle of an AngularJS Controller?

http post call not working from angularjs

I am new to AngularJS. I have included the code for the controller, service, and call to the rest service. Kindly advise why the call is not reaching the rest service.
My code is as follows:
app.config(function ($routeProvider) {
$routeProvider
.when('/addNewNote', {
controller: 'AddNewNoteController',
templateUrl:'views/addNote.html'
})
the angularjs controller is as below
app.controller('AddNewNoteController', ['$scope','savenote', function($scope,savenote) {
savenote.success(function(eData){
$scope.msg = eData;
The angular service to call the http post rest service
app.factory('savenote',['$http',function($scope,$http){
return $http({
method: 'POST',
url: <url is pasted here>,
dataType: 'json',
data: {
"title" : "123dddd",
"contents" : "123ddddtttttt"
},
headers: { 'Content-Type': 'application/json; charset=UTF-8' }
})
}]);
This is the rest service
#Path("/savenote")
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public UserMessages saveNewNote(Note note) throws IOException {
.....
}
You forgot the type hint for $scope:
app.factory('savenote',['$scope', '$http', function($scope,$http){
Also, your factory should return an object with methods:
app.factory('savenote', ['$scope', '$http', function ($scope, $http) {
return {
save: function () {
return $http({
method: 'POST',
url: "<url is pasted here>",
dataType: 'json',
data: {
"title": "123dddd",
"contents": "123ddddtttttt"
},
headers: {'Content-Type': 'application/json; charset=UTF-8'}
});
}
};
}]);
And use it as follows:
savenote.send().then(function(eData) {});
Also, as #SarjanDesai stated in his comment, $scope is not used in your factory, so you should remove it.
savenote returning $http object which has then function for calling success and failure callback.
So update your controller function with below:
savenote.then(function successCallback(eData) {
$scope.msg = eData;
}
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.

Angular factory ajax call on every route change

I have a factory where I have a function getExpenseList which does an ajax call which queries the expense table and gives me the result.
Now I have two routes, 1 which is listing of expenses which is pushing the expense through the above function and the second route is an add. When I do a route change and come back to the listing page, the ajax call is made again. Ideally I should be able to store the expense object on the first ajax call and then reference the same object till someone is manually refreshing the browser.
please help me on this. Here is my factory code. Ideally I would like to refer to this.expenses if the data is present.
admin.factory('expenseFact', ['$http', function($http) {
var expense = {};
this.expenses = "";
expense.getExpenseList = function() {
this.expenses = $http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: "GET",
url: base_url + "rest/expenses"
});
return this.expenses;
};
return expense;
}]);
And here is my controller code
admin.controller('expenseLandCtrl', function ($scope,$rootScope,expenseFact) {
$scope.pageTitle = $rootScope.pageTitle;
expenseFact.getExpenseList().then(function (data) {
$scope.expenses = data.data;
});
});
admin.controller('expenseAddCtrl', function ($scope,$rootScope,expenseFact) {
$scope.pageTitle = $rootScope.pageTitle;
});
your factory will be like this
admin.factory('expenseFact', ['$http', function($http) {
return {
getExpenseList: function() {
var expense = {};
this.expenses = $http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: "GET",
url: base_url + "rest/expenses"
});
return this.expenses;
}
}
}]);
and you can call it from controller same way and it wont call it automatically.
btw i recommend use of promises.
below is same code with use of promise
admin.factory('expenseFact', ['$http', '$q'. function($http, $q) {
return {
getExpenseList: function(){
var deferred = $q.defer();
$http({method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).
then(function(response) {
deferred.resolve(response.data);
}, function(response) {
deferred.reject(response.status)
});
return deferred.promise;
}
}
}]);
You need to get the expenses once when the factory is loaded for the first time;
admin.factory('expenseFact', ['$http', function($http) {
var expenses = null;
$http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: "GET",
url: base_url + "rest/expenses"
}).success(function (exp) {
expenses = exp;
}); // get the expenses when the factory is loaded
return {expenses: expenses};
}]);
What this does is that it makes the expenses return from the factory refer to the one-time ajax call to get the expenses.

Categories