传递数组不会被$http Angular service修改

Passing array is not modified with $http Angular service

本文关键字:http Angular service 修改 数组      更新时间:2023-09-26

我正在学习Angular,但我一直在尝试使用$http服务和JSON数组。我有一个名为names的数组。我可以在函数内显示其内容,但在函数外显示此错误:TypeError:无法读取未定义的属性'Name'。我认为阵列没有被正确修改。但我不知道为什么。我的代码来自W3shools.com (http://www.w3schools.com/angular/tryit.asp?filename=try_ng_customers_json)的一个示例。我稍微修改了一下。为什么当我想要显示名称变量的内容时,我第二次得到错误?

var names = [];
$http.get("http://www.w3schools.com/angular/customers.php")
    .success(function(response) {
        names = response.records;
        console.log("The name is: " + names[0].Name);
    });
    console.log("And now the name again: " + names[0].Name);

$http.get()是异步服务。试试下面的代码片段来检查模型上的更改:

$scope.name = [];
$http.get("http://www.w3schools.com/angular/customers.php")
    .success(function (response) {
    $scope.name = response.records;
    console.log("The name is: " + $scope.name[0].Name);
});
$scope.$watchCollection('name', function (newNames, oldNames) {
    if (newNames.length > 0) console.log("The name is: " + $scope.name[0].Name);
});

对于JavaScript和异步方法,重要的是要记住,代码的不同部分将在不同的时间范围内执行。第二个console.log语句是缩进的,但实际上不应该这样。它与$http.get()方法处于同一级别。

代码中发生的事情是发出get调用,然后JavaScript立即移动到下一行(最后一个console.log)并执行它,而不等待get方法的响应。控制台语句引用names数组,该数组从原始实例化中仍然为空,并尝试引用尚未设置的索引位置[0]和属性. name。实际上,数组在几毫秒内不会被填充。

下面是活动流程分解:

  1. names数组被声明和实例化为空
  2. $http.get()方法被调用
  3. console.log of names array(仍然为空)
  4. 一段时间后$http.get()返回一个响应,触发成功方法
  5. 如果响应成功,则使用响应记录
  6. 更新名称数组
  7. console.log的名称数组(现在与响应记录)

和代码执行:

1) var names = [];
2) $http.get("http://www.w3schools.com/angular/customers.php")
4) .success(function(response) {
    5)  names = response.records;
    6)  console.log("The name is: " + names[0].Name);
});
3) console.log("And now the name again: " + names[0].Name);

这就是异步代码的工作方式。当这段代码第一次运行时,names[]$http.get启动对"www.w3schools.com"的异步请求,并将success放入事件循环。然后console.log("And now the name again: " + names[0].Name);将运行,names仍然是[],因为success还没有运行。这就是为什么会出现错误。一旦$http.get完成,success将被调用,现在names有了一个值,log命令将按预期工作。

angular服务$http。Get是异步的。这意味着函数在.success被调用之前返回。