I am new to angular and I am trying to list my data in database .However I am gettin $scope not defined error..This is my code
productsService
.getProducts()
.success(function (data, status, headers, config) {
$scope.products = data;
console.log($scope.products);
})
.error(function (error) {
//Showing error message
$scope.status = 'Unable to retrieve product' + error.message;
});
In my product Service I have
return {
getProducts: function () {
return $http({
method: 'GET',
url: '/api/Products'
}).success(function (data) {
alert("success");
// console.log(data);
}).error(function (error) {
//Showing error message
alert("failed");
$scope.status = 'Unable to retrieve products' + error.message;
console.log($scope.status);
});
},
I am just getting failed alert. Please help!!!In backend I am able to get the data from database.
In an Angular service, you do not have access to the $scope, that is something you only have in directives and controllers. That is why you are getting an error about $scope being undefined.
Also, in your service you are returning a promise from your getProducts() method, yet you are also adding success and error handlers on to it. You should make up your mind whether you want to return the raw $http promise, or if instead you want to return a $q promise which is resolved with some transformed copy of the data returned in the $http().success() handler.
One final thing, if you are seeing the "failed" alert, that means your server is returning an error when you submit a request to /api/Products. If you go to that URL in your browser, does it work? You should look into why a basic GET request to that URL is not working.
You should not uses scope variables in your service, you service should only be used to get/update/share some data.
Here is how your service should look like
Service
return {
getProducts: function() {
return $http({
method: 'GET',
url: '/api/Products'
});
},
and in your controller for that service method you can have a .success() and .error() which you can use to set your error messages.
Controller
productsService
.getProducts()
.success(function (data, status, headers, config) {
$scope.products = data;
})
.error(function (error) {
$scope.status = 'Unable to retrieve product' + error.message;
});
Hope this helps.
Related
When I pass JSON data from AngularJS to MVC. I am getting below error.
Http request configuration url must be a string or a $sce trusted object. Received: {"method":"POST","url":"Home/SavePDDetails","datatype":"json","data":{"PD":{"Name":"qqq","Address":"www"}}}
MVC code:
[HttpPost]
public JsonResult SavePDDetails(PDDetailsDTO PD)
{
new PDDetailsDAL().SavePDDetails(PD);
return Json(new { Success = true, Message = "Success" });
}
AngularJS code
$scope.Click = function() {
console.log('clicked');
$http.post({
method: 'POST',
url: 'Home/SavePDDetails',
datatype: "json",
data: {
PD: $scope.PD
}
}).success(function(response) {
console.log('success');
console.log(response);
}).error(function(response) {
console.log('error');
console.log(response);
});
}
If data and url are passed as a properties of the config object, don't use the $http.post method. Simply use $http:
̶$̶h̶t̶t̶p̶.̶p̶o̶s̶t̶(̶{̶
$http({
method: 'POST',
url: 'Home/SavePDDetails',
̶d̶a̶t̶a̶t̶y̶p̶e̶:̶ ̶"̶j̶s̶o̶n̶"̶,̶
data: {
PD: $scope.PD
}
})
There is no need to stringify the data as the $http Service does that automatically.
Try as follow in your function.
Use JSON.stringify() to wrap your json
var parameter = JSON.stringify({PD: $scope.PD});
$http.post('Home/SavePDDetails', parameter).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
I know I amy look like foolish while asking this, but I am not able to figure this out.
I have written a service which handles the post call to the server. $q service is returning the promise back to the controller function which has called the service.
Service :
app.service('AjaxService', ['$http','$q','$log', function($http,$q,$log) {
return {
getSearchresultPost : function(url,data){
var defer = $q.defer();
$http.post(url, data)
.then(function(data, status, header, config){
defer.resolve(data);
}).then(function(data, status, header, config){
defer.reject(data);
});
return defer.promise;
}
};
}]);
Controller
app.controller("kitGuideNavigationController",['$scope','$window','$timeout','AjaxService',function($scope,$window,$timeout,AjaxService){
AjaxService.getSearchresultPost("/services/knowledge/getProducts",pathToCall)
.then(function(data){
console.log("Data ",data);
}).then(function(data){
console.log("Some Error Occured");
});
}]);
When I try to run the code I get both the consoles getting printed.
I am not getting what is getting wrong.Can someone help?
change the second "then" to "catch", should fix this. You have to do this in both cases.
app.controller("kitGuideNavigationController",['$scope','$window','$timeout','AjaxService',function($scope,$window,$timeout,AjaxService){
AjaxService.getSearchresultPost("/services/knowledge/getProducts",pathToCall)
.then(function(data){
console.log("Data ",data);
}).catch(function(data){
console.log("Some Error Occured");
});
}]);
update
also as I saw, you are using the $http, check here
You can change your service and pass a second parameter(error function) in $http.post like this(documentation: https://docs.angularjs.org/api/ng/service/$http):
app.service('AjaxService', ['$http','$q','$log', function($http,$q,$log) {
return {
getSearchresultPost : function(url,data){
var defer = $q.defer();
$http.post(url, data)
.then(function(data, status, header, config){
defer.resolve(data);
}, function(error, status, header, config){
defer.reject(error);
});
return defer.promise;
}
};
}]);
And in your controller you can pass a second parameter too:
app.controller("kitGuideNavigationController",['$scope','$window','$timeout','AjaxService',function($scope,$window,$timeout,AjaxService){
AjaxService.getSearchresultPost("/services/knowledge/getProducts",pathToCall)
.then(function(data){
console.log("Data ",data);
}, function(error){
console.log("Some Error Occured", error);
});
}]);
There is no need to manufacture a promise with $q.defer as the $http service already returns a promise:
app.service('AjaxService', ['$http','$q','$log', function($http,$q,$log) {
return {
getSearchresultPost : function(url,data){
//var defer = $q.defer();
var promise = $http.post(url, data)
//.then(function(data, status, header, config){
.then(function (response) {
var data = response.data;
//defer.resolve(data);
//return data to resolve
return data;
//}).then(function(data, status, header, config){
}).catch(function(response) {
var data = response.data;
//defer.reject(data);
//throw data to reject with value
throw data;
});
//return defer.promise;
return promise;
}
};
}]);
Also notice that the .then and .catch methods invoke their functions with a response object, not data but returning (or throwing) the data property to the handler creates a new promise that resolves (or rejects) with that value.
AjaxService.getSearchresultPost(url,pathToCall)
.then(function(data){
console.log("Data ",data);
//}).then(function(data){
}).catch(function(data) {
console.log("Some Error Occured");
});
For more information, see AngularJS $q Service API Reference - Chaining Promises
I pass two dates to the post method thro controller.The service responses back with some data based on the given input. Im using $scope.onGetData to get the data from post method, inorder to display the final result but it is not going inside the $scope.onGetData. So the question is how to fetch the response data from the service and use it inside a controller, so that I can make use of it in my view.
Controller:
$scope.computationList;
$scope.onViewLoaded = function () {
computationManagementService.getComputation($scope.onGetData);
}
$scope.onGetData = function (data,response,error) {
$scope.computationList = data;
}
$scope.calculateInput=function(start,end,htmlValidation)
{
var date={'startDate':start , 'endDate':end};
if(htmlValidation){
computationManagementService.getComputation(date,function(err,response){
console.log("pass thro controller");
});
}else{
console.log("Validation Error");
}
}
});
Service:
myApp.factory('computationManagementService', function($http, settings){
var ComputationServiceFactoryObj = {};
var _getComputation= function(date,callback){
$http({
method:'POST',
url: 'localhost:/8091/date/computation',
data: date
}).success(function(data,response,config){
callback(response);
console.log(data); // data
}).error(function (data, status, error, headers, config){
if(callback) {
callback(error);
console.log(error);
}
});
}
ComputationServiceFactoryObj.getComputation= _getComputation;
return ComputationServiceFactoryObj;
});
If you are trying to use the post method's data to the view then you can try this method And it worked for me but not sure if it is correct way of using the service.
Service:
myApp.factory('computationManagementService',
function($http, $rootScope, settings){
var ComputationServiceFactoryObj = {};
var _getComputation=function(callback){
var computationData=$rootScope.finalResult;
if(callback != null){
callback(computationData);
}
}
var _postComputation= function(date,callback){
$http({
method:'POST',
url: 'localhost:/8091/date/computation',
data: date
}).success(function(data){
callback(data);
$rootScope.finalResult=data;
console.log(data); // data
}).error(function (data, status, error, headers, config){
if(callback) {
callback(error);
console.log(error);
}
});
}
ComputationServiceFactoryObj.getComputation= _getComputation;
ComputationServiceFactoryObj.postComputation= _postComputation;
return ComputationServiceFactoryObj;
});
Some good practices:
using ngResource is always preferable to the raw $http service, except for rare cases when you need some complex configuration that ngResource can't handle (I can't think of such, though). Why? It forces you yo use promises.
return promises from your service methods instead of passing callbacks. Using callbacks will force you to call $digest on your scope so that bingings are re-evaluated, which goes against the way angular works in general and may have negative performance impact as well.
In your case I'd modify the _getComputation method to simply return a promise:
var _getComputation = function(date) {
return $http({
method:'POST',
url: 'localhost:/8091/date/computation',
data: date
});
};
In your controller:
computationManagementService.getComputation(date)
.then(function(response) {
console.log(response);
$scope.someValue = response.someValue;
}, function(error) {
console.error(error);
});
I'd rather avoid injecting $scope in controllers, and use the ngController='MyController' as 'MyCtrl' syntax instead and assign values that should be accessible by views to the controller instance.
It is better not to use .success and .error methods in your service as they are not chainable, Use .then format instead. .success/error methods are deprecated in the latest Angular version 1.6.
Here is the Deprecation notice from Angular documentaion.
In your service :
var _getComputation= function(date,callback){
return $http({
method:'POST',
url: 'localhost:/8091/date/computation',
data: date
}).success(function(data,response,config){
callback(undefined, response);
console.log(data); // data
}).error(function (data, status, error, headers, config){
if(callback) {
callback(error);
console.log(error);
}
});
}
In your Controller :
computationManagementService.getComputation(date,function(err,response){
console.log("pass thro controller");
console.log(response);
}
In a web application made with Angular I have a controller which call a service to update some data, so there are no object that return from server.
This is the angular code:
$scope.movie = Movie.update({ id: $stateParams.id });
It works but I want to alert 'Success' if it has update correctly. I've tried adding .success and .error:
.success(function(data) {
alert('Success update!');
})
.error(function(data, status) {
console.error('Repos error', status, data);
})
but console shows me this error: .success is not a function
Can you provide the full code, with the correct structure. I mean, when you use the .success
actually you can use something like this.
Movie.update({ id: $stateParams.id }).success(function(data) {
alert('Success update!');
})
.error(function(data, status) {
console.error('Repos error', status, data);
})
or
Movie.update(
{ id: $stateParams.id },
function(data){
// do something when success
},
function (error){
// do something when error
}
)
I'm quite new on AngularJS and got stumped on a problem. I'm trying to get a value from a factory and was able to get the data, I attached a console.log() to the function to check, but when I tried to attached these data on a scope and do a check using console.log again, I’m getting a undefined message on the log.
I tried creating an object scope $scope.formWO= {}; and references it there but still I’m getting the same message. I don’t know if there are conflicts between scopes or an issue of displaying the page early before the system read or perform the function. I already read a lot on scopes but for somehow this problem seem to put my development into a complete stop. I don’t know which is which and would like definitely to get enlightened on this.
Here is the trimmed down controller just to give you an idea.
myApp.controller('ordersCtrl',
function ordersCtrl($scope, ngTableParams, dealerData, costElementData, totNoData, $http, $ekathuwa, $rootScope, $location, userService, $filter){
$scope.formWO = {};
$scope.addWorkOrder = function(){
$scope.modalHeader = "ADD NEW WORK ORDER";
$scope.modalType = "Add";
$ekathuwa.modal({
id: "modalWO",
scope: $scope,
templateURL: "./tpl/modal-wo.html"
});
$scope.$watch('formWO.dealer', function(newDealer, oldDealer){
if ( newDealer === oldDealer) {
return;
}
$http.get('api/profile/'+$scope.formWO.dealer).
success(function(data, status, headers, config){
$scope.formWO.outletno = data.outletno;
});
if ($scope.dealer === newDealer) {
return;
}
});
}
$scope.submitAddWorkOrder = function(cost_element, desc, ets, etc, cost_estimate, dealer){
totNoData.getTotNo(function(noData){
$scope.formWO.totno = noData;
});
console.log($scope.formWO.totno);
$scope.tableParams.reload();
}
});
Here is the factory:
myApp.factory('totNoData', function($http, $log){
return {
getTotNo: function(successcb){
$http({method: 'GET', url: 'api/totno'}).
success(function(data, status, headers, config){
successcb(data);
}).
error(function(data, status, headers, config){
$log.warn(data, status, headers, config);
});
}
}
});
What you probably want to do is move the log and, I guess, the reload, inside of the anonymous callback function that you're passing to 'getToNo'. Like:
$scope.submitAddWorkOrder = function(cost_element, desc, ets, etc, cost_estimate, dealer){
totNoData.getTotNo(function(noData){
$scope.formWO.totno = noData;
console.log($scope.formWO.totno);
$scope.tableParams.reload();
});
}
As it is, the log and the reload are happening before the callback is invoked. The order would go something like this:
call the getTotNo method
send the http request
step back out to submitAddWorkOrder
log $scope.formWO.totno (undefined)
call $scope.tableParams.reload();
... event loop / digest
http response received, success method called
callback invoked
$scope.formWO.totno is set
Async for the win!
EDIT:
A better to pattern is to return the promise that is returned from the $http call.
So change the service to:
getTotNo: function(){
return $http({method: 'GET', url: 'api/totno'});
}
And refactor your controller function to:
$scope.submitAddWorkOrder = function(cost_element, desc, ets, etc, cost_estimate, dealer){
totNoData.getTotNo().success(function (data) {
$scope.formWO.totno = noData;
console.log($scope.formWO.totno);
$scope.tableParams.reload();
}).error(function (data, status, headers, config) {
$log.warn(data, status, headers, config);
});
}