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></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.
Aucun commentaire:
Enregistrer un commentaire