This is my controller.
sampleApp.controller('SupplierController', ['$scope', '$http', 'SupplierService', function ($scope, $http, SupplierService){
$scope.Suppliers = [];
$scope.getSuppliers = function() {
SupplierService.getSuppliers().then(function(data) {
$scope.Suppliers = data;
});
};
$scope.editSupplier = function(supplier) {
SupplierService.editSupplier(supplier);
editMode = false;
};
$scope.getSuppliers();
}]);
This is my service.
sampleApp.factory('SupplierService', function($http, $q) {
var SupplierService = {};
var SupplierList = [];
SupplierService.getSuppliers = function() {
var Info = {};
Info.Action = "GET";
Info = JSON.stringify (Info);
var req = {
url: SupplierURL,
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: Info
};
if ( SupplierList.length === 0 )
{
return $http(req).then(function (response) {
SupplierList = response.data
return response.data;
});
}
else
{
var deferred = $q.defer();
deferred.resolve(SupplierList);
return deferred.promise;
}
};
SupplierService.addNewSupplier = function(supplier) {
var Info = {};
Info.Action = "ADD";
Info.SupplierName = supplier.name;
Info.SupplierMobile = supplier.mobile;
Info = JSON.stringify (Info);
var req = {
url: SupplierURL,
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: Info
};
$http(req)
.success(function(data) {
alert ('Supplier update is successful.');
})
.error(function (data, status, headers, config) {
alert ('Supplier update error.');
});
};
SupplierService.editSupplier = function(supplier) {
var Info = {};
Info.Action = "UPDATE";
Info.SupplierID = supplier.id;
Info.SupplierName = supplier.name;
Info.SupplierMobile = supplier.mobile;
Info = JSON.stringify (Info);
var req = {
url: SupplierURL,
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: Info
};
$http(req)
.success(function(data) {
alert ('Supplier update is successful.');
})
.error(function (data, status, headers, config) {
alert ('Supplier update error.');
});
};
return SupplierService;
});
What i want is, only when http call for editSupplier is successful then only i want this line to be executed.
editMode = false;
Currently above line is in $scope.editSupplier function. so irrespective of success or failure it is getting called. How to move this line to service??
Any better approach will be highly appreciated.
The easiest way, based on your current setup, would be to return $http(req) (as that is a promise). So the end of editSupplier would say:
return $http(req);
And in your controller, you could do:
SupplierService.editSupplier(supplier).success(function(response) {
editMode = false;
});
You could additionally chain the .error handler if you have something specific to do in the case of an error.
#tandrewnichols stole my initial answer so I'll offer the alternative.:p
Move editMode into the service and use a getter to check the value of editMode.
Also, are you intending to make editMode a global variable in your application?
Related
I get a value of "True" in my response. How come my debugger and alert and AccessGranted() in the .then of my $http is not being invoked. Below is my Script:
app.controller("LoginController", function($scope, $http) {
$scope.btnText = "Enter";
$scope.message = "";
$scope.login = function() {
$scope.btnText = "Please wait...";
$scope.message = "We're logging you in.";
$http({
method: 'post',
url: '/Login/Login',
data: $scope.LoginUser
}).then(function (response) {
debugger;
alert(response.data);
if (response.data == "True") {
AccessGranted();
} else {
$scope.message = response.data;
$scope.btnText = "Enter";
}
},
function (error) {
$scope.message = 'Sending error: ' + error;
});
}
$scope.AccessGranted = function() {
window.location.pathname("/Home/HomeIndex");
}
});
This is in my HomeController
public ActionResult HomeIndex()
{
var am = new AuditManager();
var auditModel = new AuditModel()
{
AccountId = 0,
ActionDateTime = DateTime.Now,
ActionName = "Home",
ActionResult = "Redirected to Home"
};
am.InsertAudit(auditModel);
return View("Index");
}
Please see image for the response I get.
seems like your approach is wrong
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Try this,
$http({
method: 'post',
url: '/Login/Login',
data: $scope.LoginUser
})
.then(function (response) {
console.log(response);
},
function (error) {
console.log(error);
});
And check your browser console for logs or any errors
Make sure the response is application/json content type, and content is json.
You can also write own httpProvider for check result from server
module.config(['$httpProvider', function ($httpProvider) {
...
I would suggest you to code like this instead of then so whenever there is success, The success part will be invoked.
$http.get('/path/').success(function (data) {
$scope.yourdata = data.data;
//console.log($scope.yourdata);
}).error(function (error){
//error part
});
I am trying to call a factory to generate token from two different controllers
1.homeCtrl
2.savingsCtrl
but m getting same token value in both places
here is my code
---factory
app.factory('tokenFactory', ['$http', function($http) {
return $http({
method: 'POST',
url: "../api/v1/getToken",
headers : {
'Content-Type':'application/json',
'X-API-KEY':'04g4g00c04ks4sokgkoosg0kwww0cww4www0kc80',
'Authorization':"Basic cGVzYXZlQXBwOkNDNTVzV0FwUW0zYWxpazlLNTcwTTFXQ1RNOUJ1TmZS"
},
data: {"grant_type":"client_credentials"}
}) .success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
----homeCtrl
app.controller('homeCtrl', ['$scope','tokenFactory', function($scope,tokenFactory){
tokenFactory.success(function(data) {
$scope.token = data;
var token=data.access_token;
}])
----savingsCtrl
app.controller('savingsCtrl', ['$scope','tokenFactory','savingsFactory', function($scope,tokenFactory,savingsFactory){
tokenFactory.success(function(data) {
$scope.token = data;
var token=data.access_token;
var userId='9c28735e-8a29-401d-b94e-6cc90a087d96';
alert(token)
$scope.getGoals=function(){
savingsFactory.getGoals(userId,token).success(function(data) {
$scope.goals = data;
var goal=$scope.goals.goalName;
alert(goal)
});
}
You should return the $http with some method not directly in factory
app.factory('tokenFactory', ['$http', function($http) {
var getToken = function(){
return $http({
method: 'POST',
url: "../api/v1/getToken",
headers : {
'Content-Type':'application/json',
'X-API-KEY':'04g4g00c04ks4sokgkoosg0kwww0cww4www0kc80',
'Authorization':"Basic cGVzYXZlQXBwOkNDNTVzV0FwUW0zYWxpazlLNTcwTTFXQ1RNOUJ1TmZS"
},
data: {"grant_type":"client_credentials"}
}) .success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
return {
getToken : getToken
}
}]);
and then use it in controllers like this
tokenFactory.getToken().then(function (data) {
$scope.token = data.data.access_token;
var token = data.data.access_token;
alert(token);
});
I have tested this and its working
Try this:
----factory
app.factory('tokenFactory', ['$http', function($http) {
function getToken() {
$http({
method: 'POST',
url: "../api/v1/getToken",
headers : {
'Content-Type':'application/json',
'X-API-KEY':'04g4g00c04ks4sokgkoosg0kwww0cww4www0kc80',
'Authorization':"Basic cGVzYXZlQXBwOkNDNTVzV0FwUW0zYWxpazlLNTcwTTFXQ1RNOUJ1TmZS"
},
data: {"grant_type":"client_credentials"}
})
}
return {getToken: getToken}
}]);
----homeCtrl
app.controller('homeCtrl', ['$scope','tokenFactory', function($scope,tokenFactory){
tokenFactory.getToken()
.success(function(data) {
$scope.token = data;
var token=data.access_token;
}
}])
----savingsCtrl
app.controller('savingsCtrl', ['$scope','tokenFactory','savingsFactory', function($scope,tokenFactory,savingsFactory){
tokenFactory.getToken()
.success(function(data) {
$scope.token = data;
var token=data.access_token;
var userId='9c28735e-8a29-401d-b94e-6cc90a087d96';
alert(token)
$scope.getGoals=function(){
savingsFactory.getGoals(userId,token).success(function(data) {
$scope.goals = data;
var goal=$scope.goals.goalName;
alert(goal)
});
}
}])
i want to get just my service in the variable from my controller but it give me an $$state object
this is my controller
$scope.myDataSMS = ServiceSms.async().then(function(data){
$scope.myDataSMS1 = data;
console.log($scope.myDataSMS1);
return $scope.myDataSMS1;
});
console.log($scope.myDataSMS);
and my service
routeAppControllers.factory('ServiceSms', function($http,Token) {
var key = Token.CreateToken()
var myService = {
async: function() {
var data = 'token=' + encodeURIComponent(key);
var promise = $http({
method: 'POST',
url: 'PhpFunction/getsms.php',
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(data) {
// The then function here is an opportunity to modify the response
// console.log(data.data);
// The return value gets picked up by the then in the controller.
return data.data;
})
// Return the promise to the controller
return promise;
}
};
return myService;
});
i think that the problems is with the promise but there i m little bit stuck
if someone can help me please
thanks in advance
this would be a better way to write your promise:
CONTROLLER:
.controller('nameofcontroller', ['$scope', 'ServiceSms', function($scope, ServiceSms) {
$scope.myDataSMS = ServiceSms.async()
.then(
function(data){
$scope.myDataSMS1 = data;
console.log($scope.myDataSMS1);
return $scope.myDataSMS1;
},
function(err){
console.log('err: ' + err);
});
}]);
SERVICE:
routeAppControllers.factory('ServiceSms', function($http,Token) {
return {
async: function() {
var data = 'token=' + encodeURIComponent(key);
return $http({
method: 'POST',
url: 'PhpFunction/getsms.php',
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
}
}
});
This code fetches categories and give them to controller.
sampleApp.factory('SCService', function($http, $q) {
var SuperCategories = [];
var SCService = {};
SCService.GetSuperCategories = function() {
var req = {
method: 'POST',
url: SuperCategoryURL,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "action=GET"
};
if ( SuperCategories.length == 0 ) {
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
});
}else {
return $q.when(SuperCategories);
}
}
return SCService;
});
I think code is perfect until there is no error in http request.
My query is how to do error handling (try catch or something like that), in case if server have some issue or may be cgi-script have some issue and not able to server the request.
Angular promises use a method catch for that.
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
}).catch(function(error) {
// Do what you want here
});
You should use also finally :
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
}).catch(function(error) {
// Do what you want here
}).finally(function() {
// Always executed. Clean up variables, call a callback, etc...
});
Write like
return $http(req).then(function (response) {
//success callback
},
function(){
//Failure callback
});
Use callback methods from controller Like
Controller.js
service.GetSuperCategories(function (data) {console.log('success'},function (error){console.log('error'});
service.js
sampleApp.factory('SCService', function($http, $q) {
var SuperCategories = [];
var SCService = {};
SCService.GetSuperCategories = function(successMethod,errorMethod) {
var req = {
method: 'POST',
url: SuperCategoryURL,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "action=GET"
};
return $http(req).then(successMethod(data),
errorMethod(error));
}
return SCService;
});
You can use the .success and .error methods of $http service, as below
$http(req).success(function(data, status, headers){
// success callback: Enters if status = 200
}).error(function(status, headers){
// error callback: enters otherwise
});
myapp.factory('serviceName', function( $http, webStorage){
var factory = {};
var resoureurlBase=some base url;
factory.genericService = function(method, payload, methodName, callbackFn, callbackError, param) {
var httpRequest = null;
if (param && param == true) {
httpRequest = $http({
url: resoureurlBase+methodName,
method: method,
params: payload,
headers: {
'Content-Type': 'application/json'
}
});
} else {
httpRequest = $http({
url: resoureurlBase+methodName,
method: method,
data: payload,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
}
httpRequest.then(function(response) {
if (callbackFn && callbackFn.call) {
callbackFn.call(null, response);
}
},
function(response) {
if (callbackError && callbackError.call) {
callbackError.call(response);
}
});
httpRequest.error(function(data, status, headers, config) {
});
};
return factory;
});
/*
I have written service like above how can i handle in controller
i mean
how to write call back function in controller
how to inject
etc..
*/
Simple DI(dependency injection) it into your controller:-
myapp.controller('myCtrl',['$scope','serviceName',function($scope,serviceName){
// use serviceName to call your factory function
}]);
Ref:- https://docs.angularjs.org/guide/di
You need to call service like
serviceName.genericService(--parmas--).then(function(d){
//success
})
because from service serviceName, you're returning a promise that need to resolved using .then only.
Controller
var mainController = function($scope, serviceName) {
var callbackFn = function() {
console.log('Success');
}
var callbackError = function() {
console.log('Error');
}
var parameter = {
param1: 1
},
method = 'something', payload = 100, methodName = 'something';
serviceName.genericService(method, payload, methodName, callbackFn, callbackError, parameter).then(
//success function
function(data) {
//call after call succeed
},
//error function
function(error) {
//call after call error
});
};
myapp.controller('mainController', ['$scope', 'serviceName', mainController()];
Hope this could help you. Thanks.