i using angular 1.5.
i can't access data, http.get, out http.get. let me explain:
i have component:
(function(){ 'use strict'; class mycomponent { constructor( $http, $scope) { var self = this; self.test="this test"; $http.get(myapi).then(function(response){ self.mydata = response.data; console.log(self.mydata) }); console.log(self.test) console.log(self.mydata) } } angular.module('myapp') .component('myapp.test', { templateurl: 'mytemplate.html', controller: mycomponent, controlleras:'vm', }); })();
the console.log give me:
this test --> test
undefined --> out http.get
object {id: 1…} --> in http.get
so can't access data out http.get , want.
have idee? thank you.
$http.get
asynchronous call meaning program execution doesn't wait data fetched server .
thus time console.log(self.mydata)
located outside of $http.get()
executed , data has not been fetched server why undefined error
.
to solve problem or handle asynchronous calls , :
var promise = $http.get(myapi);
then access data in following manner of callbacks :
promise.then( function successcallback(response) { self.mydata = response.data; console.log(self.mydata) } ).then( function errorcallback(response) { console.log(response); } );
here nice article on callbacks !
Comments
Post a Comment