How to display reponse data (get) from server in AngularJS
in my code I need to alert $scope.orders inside that controller but it willll not show..
function OrderController($scope,$http)
{
var orderPromise = $http.get("../api/order");
orderPromise.success(function(data, status, headers, config)
{
$scope.orders=data
alert(JSON.stringify($scope.orders)) // First alert
});
orderPromise.error(function(data, status, headers, config)
{
alert("Error");
});
alert(JSON.stringify($scope.orders)) // Second alert
}
How can i access $scope.orders to outside the success fun()
Here I am alerting $scope.data in two times
In here First Alert is shown
but Second Alert is nothing to show why?
How to show second one?
Second alert will not show because there's nothing in $scope.orders when you alert it. That's the nature of asynchronous calls, only when you enter the success/error sections will you have something there (or not...).
Until the server returns your response and the success/error functions trigger, that variable is still unpopulated since $scope.orders=data hasn't run.
You should read the docs for some more info, and get some deeper understanding into how promises work.
Related
How to can access $scope.categories outside the promise success function
var categoryPromise = $http.get("../rest/mcategory");
categoryPromise.success(function(data, status, headers, config)
{
$scope.categories=data;
});
categoryPromise.error(function(data, status, headers, config)
{
alert("Error");
});
alert(JSON.stringify($scope.categories));
I got undefined in each time Why? Any way to access outside?
A $http call is asynchronous, this means that it doesn't execute in order of your code, the actual order of your code is as following:
Initialise categoryPromise $http
alert
categoryPromise finishes
categoryPromise success callback
So if you want to use the data from categoryPromise you have to do it in the success callback.
Side note: don't use .success, it's deprecated. Use .then instead like so:
promise.then(successCallback, errorCallback);
As Martijn points out, if you want to use it for direct modification you'll have to do it into the callback as the XHR request won't be finished.
However if you put this into your $scope, it's maybe because you'll use it into your view with data binding into the DOM. In that case Angular is pretty neat because, when the promise will be resolved, at the next $digest cycle it will populate with your category object all of the {{category.strings}} in your $scope realm.
Would love to post that in a comment but don't have 50 rep.
The problem here is angular hits that url and continues to execute the code after that without waiting for response that's why here maybe url is hit by browser but when execution reached to assign categories it got undefined.
Solution:
var categoryPromise = $http.get("../rest/mcategory");
categoryPromise.success(function(data, status, headers, config)
{
$scope.categories=data;
alert(JSON.stringify($scope.categories));
});
categoryPromise.error(function(data, status, headers, config)
{
alert("Error");
});
There is a strange behaviour in my AngularJS application. The use case it to create a user at "usercreate.html" and after successfully creating (over Backend REST- Service -> HTTP POST) a redirect to "usercreateresponse.html" is made.
I have two controllers:
usercreate.html -> CreateUserController
usercreateresponse.html -> CreateUserResponseController
and I share the data between CreateUserController and CreateUserResponseController over $rootScope.$broadcast and $rootScope.$on.
My problem now is, that when I have changed something in the code (AngularJS code) and I refresh the browser page and afterwards I will create a user, the user creation works fine and I am also redirected to usercreateresponse.html but no values are shown -> but this is only the first time -> if i navigate back to usercreate.html and create a user once again everything works fine.
I found out that in case if it is not working, a HTTP GET is made to get the HTML- Code from the back end. In case it works than only HTTP POST is made an everything works fine.
Does anybody know how to prevent the first user creation -> redirect problem?
Here the controller/services:
function CreateUserController($scope, CreateUserService) {
$scope.createUser = function(data) {
CreateUserService.createUser($scope.usernameCreate, $scope.passwordCreate, $scope.role);
}
}
services.factory('CreateUserService', function($rootScope, $location, $http) {
...
var res = $http.post('/users/createUser', dataObj);
res.success(function(data, status, headers, config) {
$rootScope.$broadcast('handleCreatedUser', {usernameCreate: data.username, passwordCreate: data.password, role: data.roles});
$location.path("usercreateresponse");
});
res.error(function(data, status, headers, config) {
...
});
}
return sharedCreateUserService;
});
function CreateUserResponseController($rootScope) {
$rootScope.$on('handleCreatedUser', function(event, args) {
$rootScope.usernameCreated = args.usernameCreate;
$rootScope.passwordCreated = args.passwordCreate;
$rootScope.role = args.role[0];
});
}
Instead of a broadcast, you can use a service which will store the response of the Creation of user. Then you can share it using the service with the CreateUserResponseController. With broadcast event, what might be happening is, you are broadcasting an event before the controller which handles it is instantiated. So, the $on may not have registered till then. And hence the issue you face.
I am starting to build a web application.
The user can select and add items to a list of fruit. The list of fruit objects is stored in an array in Javascript/AngularJS.
When the user presses the Submit button, I want the entire list of fruit to be sent to the server, where the list is then saved into a database.
I have only a basic understanding of HTTP. Would I want to POST the array? How would I do this?
I'd prefer you to go for $resource which includes in ngResource module.
While passing array inside your post call you need to mention isArray option to true inside $resource option
CODE
angular.module('app',[])
//factory will have resource object
.factory('myService',function($resource){
var postFruitData = function(){
return $resource('/savefruit', {}, {saveData: {method:'POST', isArray: true}});
}
return{
saveData: postFruitData
}
})
.controller('mainCtrl',function($scope,myService){
//this function needs to be call on post like form ng-submit
$scope.postFruitData = function(){
myService.saveData({}, $scope.data).$promise.then(function(data){
//you will get data here
});
}
});
For more info you can also take look at this SO Question
Hope this could help you. Thanks.
Here's a POST example that posts an array of fruit to the server. This code would be located inside your button click function.
$scope.fruit = [{name: 'Apple'}, {name: 'Grape'}];
// Simple POST request example (passing data) :
$http.post('/someUrl', {fruit: $scope.fruit}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Take a look at the angular documentation for $http. This should help you out.
Assume I have a directive that contains a form where a user can enter in the name of a fruit.
I have a FruitFindController. User enters fruit name, "Apple", clicks a button which submits to controller.
Controller calls a service "GetFruitInfo(fruit)" and passes in "Apple" as parameter.
Once the information is received, it should call a method "addToListAndDoStuff()" in order to add the fruitinfo to the list.
My issue is, in my FruitFindController (assume fruitFinder is the service)...
$scope.GetFruitInfo = function() {
$scope.foundFruit = fruitFinder.GetFruitInfo($scope.fruitField);
// should alert "Found Fruit" and call addToListAndDoStuff() method to add the foundFruit information to the list managed by another directive, "FruitList".
}
What is the best way to "wait for the information is stored into $scope.foundFruit before doing any code below and popping up the alert box?
The best way is to use a promise. In your fruitFinder service, the GetFruitInfo method would look something like this..
function GetFruitInfo(fruit) {
var delay = $q.defer();
$http({method: 'GET', url: 'http://myapi.com/getFruitInfo?fruit=' + fruit}).
success(function(data, status, headers, config) {
delay.resolve(data);
}).
error(function(data, status, headers, config) {
delay.reject(data);
});
return delay.promise;
}
This method returns a promise object that you can wait for it to resolve in your controller using the .then() method, like this..
$scope.GetFruitInfo = function() {
$scope.foundFruit = fruitFinder.GetFruitInfo($scope.fruitField).then(function(response) {
alert('Found Fruit');
addToListAndDoStuff(response);
});
}
I have the following code which make seperate requests for jsonp data.
In the code "doRequestA" works fine and returns a result. The issue I have is
I need to catch any errors if they occur. I have tried implementing this in
"doRequestB", but only receive the alert error (I have ommitted the callback from doRequestB).
Here is the fiddle http://jsfiddle.net/a4Rc2/417/
function jsonp_callback(data) {
alert(data.found);
}
function jsonp_example($scope, $http) {
$scope.doRequestA = function () {
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=jsonp_callback";
$http.jsonp(url);
};
$scope.doRequestB = function () {
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts";
$http.jsonp(url)
.success(function (data) {
alert(data.found);
}).error(function (data, status, headers, config) {
alert('error');
});
};
}
Any advice is greatly appreciated, thanks in advance.
You actually are using $http.jsonp incorrectly in both cases. You just can't see the error in the first case because you are not handling it.
With Angular.js's $http.jsonp method, the callback method is handled automatically. You shouldn't use your own methods in the result string, but rather insert JSON_CALLBACK (exactly as written) into your string. This way, you can handle the response using the promise returned from Angular. If you watch the network activity (say, using Firebug or the developer tools in your browser of choice), you'll see JSON_CALLBACK replaced with something like angular.callbacks._0*.
In the second example, you don't have a callback method defined at all, so the result will always error. There's actually no way for the jsonp result to be handled, since it simply returns the JSON object without a callback method, and the result just is ignored.
Here's a working result: http://jsfiddle.net/tPLaN/1/
The code:
function jsonp_callback(data) {
alert(data.found);
}
function jsonp_example($scope, $http) {
$scope.doRequestA = function() {
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
$http.jsonp(url).success(function(data) {
jsonp_callback(data);
});
};
$scope.doRequestB = function() {
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function (data) {
alert(data.found);
}).error(function (data, status, headers, config) {
alert('error');
});
};
}
The only thing I changed was
Correcting the two URLs.
Moving the callback handler on the first method inside the .success() method on the promise.
Believe it or not, the need for JSON_CALLBACK is in the documentation for $http.jsonp, but it's sort of hidden.
* Note, please do not use the replacement for JSON_CALLBACK for anything. It's a private method generated by Angular, I am just showing it to help make more sense of what is happening.