0

Im tryin to access my $rootScope.newBloodneeded but I cant access it outside the function, I tried rootscope so I can call it as global but still it gives me undefined

.controller('editbloodrequestCtrl', function($scope,Bloodrequest,$rootScope,$routeParams) {
$rootScope.newBloodneeded;

Bloodrequest.getBloodrequest($routeParams.id).then(function(data) {
        if (data.data.success) {
            $scope.newBloodneeded = data.data.bloodrequest.blood_component;
            $rootScope.newBloodneeded = $scope.newBloodneeded;
            //gives me output when I console here
        } else {
            app.errorMsg = data.data.message; // Set error message
        }
    });

console.log($rootScope.newBloodneeded); //gives me undefined

}
  • Hello. Welcome to StackOverflow! What you're seeing here is a common JS problem - You are accessing a value before it's set asynchronously. There are a lot of similar questions out there like [this](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call), [this](https://stackoverflow.com/questions/48303536/angularjs-getting-data-from-asynchronous-call) – Chirag Ravindra Mar 15 '19 at 00:19
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Chirag Ravindra Mar 15 '19 at 00:23

1 Answers1

0

Assuming $rootScope is working correctly, this is a problem of asynchronicity NOT scope—when you try to run:

console.log($rootScope.newBloodneeded); //gives me undefined

...getBloodRequest has not necessarily finished. You set the $rootScope.newBloodneeded in the then, which is ONLY run after getBloodRequest resolves, which may be far, far after your console log finishes.

Bloodrequest.getBloodrequest($routeParams.id).then(function(data) {
            ...
            $rootScope.newBloodneeded = $scope.newBloodneeded;
            ...

One fun test you can try is to wrap that console log in setTimeout for a LONG time (when you are guaranteed/sure that getBloodRequest has finished). That should prove to you that timing is the issue, not one of function scoping.

Basically:

setTimeout(() => console.log($rootScope.newBloodneeded), 10000000000) // or whatever timing guarantees completion

The solution here is to also chain whatever logic that requires $rootScope.newBloodneeded in .then. If THAT doesn't work, you might want to create a Promise that you access from elsewhere. (That's beyond the scope of this question, and we'd need more detail to figure out best implementation).

James Wang
  • 1,281
  • 9
  • 17