i will get data from function, in case this my code..
var urlServer = 'http://localhost:2205/inventoryApp/server/';
$scope.getReport = function() {
$http.get( urlServer + 'transaksi.php?action=getreport').success(function(data) {
$scope.reports = data;
// console.log($scope.reports.tanggal);
// if i run this console (inside function) the data is showing in console log
});
};
$scope.getReport();
console.log($scope.reports);
//this console log get undefined
and i get undefined in my console log..
thanks before :)
Your code runs synchronously, your request runs asynchronous, so this should work:
var urlServer = 'http://localhost:2205/inventoryApp/server/';
$scope.getReport = function() {
$http.get( urlServer + 'transaksi.php?action=getreport').success(function(data) {
$scope.reports = data;
// console.log($scope.reports.tanggal);
// if i run this console (inside function) the data is showing in console log
console.log($scope.reports);
});
};
$scope.getReport();
window.setTimeout(function()
{
console.log('data should be available now', $scope.reports);
}, 5000);
You just have to wait until your request is finished before you can display its response. :-)
For example, after a few seconds, your data should be available. To make this clean, use promises as you can see here: https://docs.angularjs.org/api/ng/service/$http
console is executed before executing get service. try to use .then() function and console in it.
Related
testAngular(); //**(1º)**
function testAngular() {
var uri = 'some_webmethod_url';
var data = {
"key": "anything"
};
var res = $http.post(uri, data);
res.then(function (data) {
console.log(data); //**(2º)**
});
console.log(data); //**(3º)**
}
console.log(data); //**(4º)**
The actual sequence is 1º -- 3º -- 4º -- 2º; Why?
And more importantly, how can I make this in that sequence? (1º -- 2º -- 3º -- 4º)
Since the 'then' is a callback and called asynchronously when the response from the server becomes available (after the POST request is completed). So the statement console.log(data); //**(2º)** will be executed only after the response is received but rest of other processing will continue.
If you want the order that you mentioned, you will have to make those statement as part of the callback. The other option is to make the callbacks synchronous which is not supported out of the box by Angular JS but you can look into the source code and make changes. This SO post might help you in that https://stackoverflow.com/questions/13088153/how-to-http-synchronous-call-with-angularjs
Or a small hack as mentioned in other SO post might help you AngularJs: Have method return synchronously when it calls $http or $resource internally though it's not recommended.
testAngular(); //**(1º)**
function testAngular() {
var uri = 'some_webmethod_url';
var data = {
"key": "anything"
};
var res = $http.post(uri, data);
res.then(function (data) {
console.log(data); //**(2º)**
console.log(data); //**(3º)**
console.log(data); //**(4º)**
});
}
I have been trying to make an http call for a while but I am stuck here as I am not able to resolve the actual data value from the returned $$state variable. This is my code:
function (action, req){
var myData = $http.post('../rest/'+action, req)
.then(function(response) {
var data= response.data;
console.log("data: "+data); //1st console
return data;
},
function(response) {
alert(JSON.stringify(response));
});
console.log(myData); //2nd console
}
In the first console the values comes out to be fine as:
data: This is my data.
However when I return the same value and print it in the second console it is wrapped up in a $$state object. This is my second console:
d { $$state={...}, then=function(), catch=function(), more...}
When i expand it i get this value(in window>d):
Please help. What i need to do next to get $$state.value or d.$$state.value?
My service define like this:
module.factory('portfolio',function(){
var data;
var selectedPort;
return{
getData: function(){
return data;
},
setData:function(portfolios){
data = portfolios;
},
getSelectedPort:function(){
return selectedPort;
},
setSelectedPort:function(portfolioDetail){
selectedPort = portfolioDetail;
}
}
});
And in my controller the code as follows:
module.controller('portfoliosController', function($scope,$http, alertService,stockService, userDataService, portfolio){
var req = {
method: 'get',
url: 'www.facebook.com',
headers: {
'Authorization': userDataService.getToken()
}
};
$http(req).then(function(reponse){
$scope.portfoliosPriceList = reponse['data'];
portfolio.setData($scope.portfoliosPriceList);
console.log(portfolio.getData())//At here,I can get the portfolio's data
}, function(){
alertService.setMessge("System maintenance , please try again later");
alertService.alert();
});
console.log(portfolio.getData())//At here, I cannot get the portfolio's data
});
the error is
Error: undefined is not an object (evaluating 'message.substr')
Anybody can help me to solve this problem?Actually, I really do not understand, why I cannot get the data outside the $http
The request that you do with the $http service is done asynchronously, so the callback that you pass to the .send is not immediately invoked.
The code that follows (the console.log) is executed just after the $http(req) call is made but before the callback is called when the request is responded.
Maybe you will understand better with an simpler example:
function portfoliosController() {
var data = 'Initial Data. ',
content = document.getElementById('content');
// setTimeout would be your $http.send(req)
// calledLater would be your .then(function() { ... })
setTimeout(function calledLater() {
data = 'Data coming from the server takes some time to arrive...';
content.innerHTML = content.innerHTML + data;
}, 1000);
content.innerHTML = content.innerHTML + data;
}
portfoliosController();
<div id="content">
This is because javascript is asynchronous, so the code:
portfolio.getData()
Is maybe executing before the data is returned from the service.
In this case, you should only use the data of the portfolio just after the request is complete (inside the .then() function of $http) or put a promise.
Here is the documentation for angular promises:
https://docs.angularjs.org/api/ng/service/$q
I am following an AngularJS tutorial that uses $resource to retrieve JSON data from an API call. For the purpose of understanding, I tried to replace the $resource code with $http code and I encountered a scope problem. Logging $scope.weatherResult outside of .success() results in undefined. Why is that the case? The view receives the data just fine.
Also,
// $scope.weatherAPI = $resource(
'http://api.openweathermap.org/data/2.5/forecast/daily',
{ callback: 'JSON_CALLBACK' }, { get: { method: 'JSONP' }}
);
// $scope.weatherResult = $scope.weatherAPI.get({ q: $scope.city, cnt: 2});
$http.get('
http://api.openweathermap.org/data/2.5/forecast/daily'
+ '?q='
+ $scope.city
+ '&'
+ 'cnt=2'
)
.success(function(data) {
$scope.weatherResult = data;
})
.error(function(error) {
console.log(error);
});
console.log($scope.weatherResult);
Because $http is asynchronous.
$scope.weatherResult is defined only when the http response is available.
See for example http://code.tutsplus.com/tutorials/event-based-programming-what-async-has-over-sync--net-30027, or better, as PSL says: How do I return the response from an asynchronous call?
You can use $watch to be informed:
$watch('weatherResult',function(newValue,oldValue)) {
..
}
When you write
.success(function(data) {
$scope.weatherResult = data;
})
in your program, you are asking the remaining part of your code to continue its execution with a promise.
In this case console.log($scope.weatherResult);
will be executed just after your $http.get() method without waiting for the response from the http request.
Hence, console.log($scope.weatherResult); will be executed even before the API response is received.
Note that $scope.weatherResult is defined inside .success(), so until the response is a success, Angular has no idea about $scope.weatherResult hence the console gives undefined. It will be undefined even in case of an error.
To view the response of server, you can log it well inside success block.
.success(function(data) {
$scope.weatherResult = data;
console.log("$scope.weatherResult = ",$scope.weatherResult);
})
I'm facing the following problem and I can't get rid of it :
I've got an Angular app that calls an API using $http.post,
this api call make an update to the database and wait 10 sec before returning,
on return of the call, a dialogue is open on the browser saying that test is terminated
When I try to test this small app with Protractor, the test ends before the step 3 occurs. This make my test fail because update in database is not always done. During the test, I see the dialogue opening after 10 sec.
Here is some code.
My Angular service doing the call :
$http.post(url, parameters).
success(function (data) {
$log.debug('Success in cldHttp data is "%s"', JSON.stringify(data));
NotifSrv.translateMessage('commons.request.ok', [],
function (successMessage) {
data.errorMessage = null;
if (options.notifySuccess) NotifSrv.addNotification(successMessage, 'success');
if (cb) cb(undefined, data);
});
});
My Protractor test :
browser.get('/#!/activate-account.html?id=' + acc._id).then(function () {
browser.sleep(1000);
// Check that DB is updated
accountColl.findOne({
pseudo: 'MyActivatePseudo'
}, function (err, acc2) {
expect(err).to.not.exist; // OK
expect(acc2.activated).to.be.true; // KO the DB update has been done just after the findOne
});
});
I try the browser.sleep() in the protractor test but it does nothing.
Many thank's for your help because I'm totally stuck!
JM.