0

I am fairly new to both javascript and angular. My code retrieves data from an API and can print it to the console, but when I try to assign it to $scope.saveData, it only works inside the fetch. I've gotten as far as understanding that my problem has something to do with the code running asynchronously and the way promises work, but I can't seem to find any resources that work to solve my problem. Here is my code.

Angular

angular.module('myApp',[])
.controller('testCtrl',['$scope',  function($scope){

   const response = await fetch("http://localhost:3000/conferences").then(res=>{
      // $scope.saveData = null;
        if(res.url == "http://localhost:3000/outlook"){
            res.json().then(data=> {
                window.location.replace(data.url)
            })
       }else{
           res.json().then(data=> {
            $scope.saveData = data
            console.log($scope.saveData)
           });
       }
   });
   console.log($scope.saveData)
}]);

html

<!DOCTYPE html>
<html ng-app = 'myApp'>
    <head>
        <title>Scheduled Calls</title>
        <link rel="stylesheet/less" type = "text/css" href="./scheduledCalls.less" />
    </head>
    <body>
        <header style="text-align: center">
            <h1 class = "header" >Scheduled Calls</h1>
        </header>
        <div ng-controller="testCtrl" >
            <p>{{saveData}}</p>
        </div>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
        <script src = "scheduledCalls.js"></script>
    </body>
</html>

the console.log under $scope.saveData = data works. It does not work for the console.log at the bottom of the js code.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
Tom Kaizer
  • 80
  • 10
  • Frankly, I think it is easier to use the AngularJS [$http Service](https://docs.angularjs.org/api/ng/service/$http) than use the raw JavaScript [fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). – georgeawg Aug 01 '18 at 01:25

1 Answers1

2

What are you trying to accomplish? Why is logging $scope.saveData inside of the callback insufficient?

As you mentioned, the issue is because fetch occurs asynchronously. Inside of .then(...), it is guaranteed that the contents of localhost:3000/conferences has been retrieved. Since this call is asynchronous, it means the code may execute out of order. The following is happening:

(1) fetch call to localhost:3000/conferences is made

(2) console.log($scope.saveData) is executed (this value has not been assigned yet)

(3) results from fetch call are returned and everything in .then(...) executes (this console.log($scope.saveData) works because it is guaranteed that fetch has completed

If you absolutely must have the code wait for the results of fetch, I would suggest taking a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

Aaron Leon
  • 116
  • 3
  • my problem is I would like to reference the value stored in $scope.saveData in the corresponding html file and at the moment nothing is getting printed to the view. I guess my question is really how I can store that data in a way that can be retrieved in the html file. Sorry for the lack of clarity – Tom Kaizer Jul 31 '18 at 19:34
  • @TomKaizer Is this just a case where the fetch is resolving outside the Angular digest cycle? If so you can wrap your assignment to the `$scope` variable in a `$scope.apply()`. – Lex Jul 31 '18 at 20:00
  • That worked! thanks I had been stuck on that for a long time. – Tom Kaizer Jul 31 '18 at 20:29