【问题标题】:How do I assign fetch data to $scope.variable [duplicate]如何将获取数据分配给 $scope.variable [重复]
【发布时间】:2019-01-08 06:15:16
【问题描述】:

我对 javascript 和 angular 都很陌生。我的代码从 API 检索数据并可以将其打印到控制台,但是当我尝试将其分配给 $scope.saveData 时,它只能在 fetch 内部工作。据我所知,我的问题与异步运行的代码和承诺的工作方式有关,但我似乎找不到任何可以解决我的问题的资源。这是我的代码。

角度

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>

$scope.saveData = data 下的 console.log 有效。对js代码底部的console.log不起作用。

【问题讨论】:

标签: javascript html angularjs web


【解决方案1】:

你想完成什么?为什么在回调中记录$scope.saveData 不足?

正如您所提到的,问题是因为fetch 异步发生。在.then(...)内部,保证localhost:3000/conferences的内容已经被检索到。由于此调用是异步的,这意味着代码可能会乱序执行。正在发生以下情况:

(1) 获取到 localhost:3000/conferences 的调用

(2) console.log($scope.saveData) 被执行(这个值还没有赋值)

(3) 返回 fetch 调用的结果并执行 .then(...) 中的所有内容(此 console.log($scope.saveData) 有效,因为它保证 fetch 已完成

如果您绝对必须让代码等待获取结果,我建议您查看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

【讨论】:

  • 我的问题是我想在相应的 html 文件中引用存储在 $scope.saveData 中的值,目前没有任何内容打印到视图中。我想我的问题实际上是如何以可以在 html 文件中检索的方式存储这些数据。抱歉,不清楚
  • @TomKaizer 这只是获取在 Angular 摘要循环之外解析的情况吗?如果是这样,您可以将分配给$scope 变量的值包装在$scope.apply() 中。
  • 成功了!谢谢我已经坚持了很长时间。
猜你喜欢
  • 2021-12-31
  • 1970-01-01
  • 2021-08-04
  • 1970-01-01
  • 1970-01-01
  • 2014-06-27
  • 2012-08-05
  • 2021-10-26
  • 1970-01-01
相关资源
最近更新 更多