gpt4 book ai didi

Angular : Multiple Calls for $http service

转载 作者:可可西里 更新时间:2023-11-01 17:05:36 26 4
gpt4 key购买 nike

这是我的代码:

        var updateScreen = function() {
$http.get("http://localhost:5000").then(function(response){
$scope.numSerie = response.data.refDetail.Num_Serie;

$http.get("data/tempsgammes.json").then(function(res){
$scope.time = res.data[$scope.numSerie].temps;
console.log($scope.time)
})

console.log($scope.time)
}

第一个 $http.get("http://localhost:5000 ") 返回我在其余代码中使用的详细信息列表,我们感兴趣的是变量 numSerie

根据numSerie的值,将执行另一个$http.get("data/tempsgammes.json") 来提取此时间来自 JSON 文件的 numSerie

问题是我无法仅在第二次调用 $http 时访问 $scope.time。第一个 console.log() 给了我想要的结果,但第二个 undefined

谁能帮帮我?

最佳答案

编辑:console.log($scope.time) 被调用了 2 次。您会看到第一个给出了正确的值,而第二个则没有。这是因为“then”的异步行为。它不直观,但在“then”完成之前调用了第二个 console.log($scope.time),这就是它显示“undefined”的原因。

编辑 2:尝试以下方法来探测异步操作的执行顺序

 $http.get("data/tempsgammes.json").then(function(response){
alert('first'); // <--- This will be called first
.then(function(res){
alert('third!'); // <--- This will be called third
});
alert('second!'); // <--- This will be called second

是的,您可以在任何地方使用 $scope.time,但是如果您尝试在“then”后面使用它,它还不会被定义。您可以在 View {{$scope.time}} 的某处放置并探测它将在 $http.get 之外定义


如果得到 undefined 可能是 res.data[$scope.numSerie] 的索引超出范围。

首先检查您使用浏览器的开发者工具是否有错误。 $scope.numSerie 似乎是这里的罪魁祸首,请检查其值或提供更多详细信息

关于 Angular : Multiple Calls for $http service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45787605/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com