I'm trying to get some data from a Service into a Controller and I keep get an undefined variable.
angular
.module("classes")
.service("MyService", function ($http) {
this.foo;
$http.get("/classes/all").then(function (response) {
this.fighters = response.data;
this.foo = this.fighters;
console.log(this.foo);
});
console.log(this.foo);
})
When I run this I get on the console, by this order, line 11 is undefined and then line 9 returns me the array.
And when in the controller I try to get the variable foo, it also says undefined.
$scope.fooFighters = MyService.foo;
To add or overwrite these defaults, simply add or remove a property from these configuration objects. To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g. $httpProvider. defaults.
The AngularJS $http service makes a request to the server, and returns a response.
$http is an AngularJS service for reading data from remote servers. The $http is a core AngularJS service that is used to communicate with the remote HTTP service via browser's XMLHttpRequest object or via JSONP.
Use the HttpClient.get() method to fetch data from a server. The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received. The return type varies based on the observe and responseType values that you pass to the call.
The reason is because of asynchronous execution of your API call. I would suggest you to rewrite the code to use a factory that will return a promise object. No need to bring unnecessary variables.
angular.module("classes").factory("MyService", function($http) {
return {
fighters: function() {
return $http.get("/classes/all").then(function(response) {
return response.data;
});
}
}
})
And in your controller, you can get the value by injecting the service in the controller and then by referencing it like
MyService.fighters().then(function(data){
$scope.fooFighters = data;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With