5

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;

2 Answers 2

6

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;
  });
Sign up to request clarification or add additional context in comments.

8 Comments

if add console.log($scope.fooFighters); right after in the controller. I get first undefined for the variable in the controller and then I get the array from the service console.log(this.fighters);
Try the above code. Change your service to a factory to return a promise object.
I jus tried it. it keeps logging "undefined" on the console
Where are you printing $scope.fooFighters? You should put console inside then
Ohhh!! Ir has to be inside of MyService.fighters ()?so the whole controller depending on that service will have to inside of that too. Is this a good practice?
|
0

because it will take some time to load the ajax/http request data after that line 9 will work. So if you want to work with ajax/http data then you should write code/function inside

$http.get("/classes/all").then(function (response) {
        // do something
    });

1 Comment

The problem is If I want to access it in the controller. It will only do the http after running the controller

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.