【问题标题】:TyperError: Cannot read property 'length' of undefinedTypeError:无法读取未定义的属性“长度”
【发布时间】:2020-06-12 03:42:52
【问题描述】:

我们的团队正在使用 angularjs 开发 ServiceNow 小部件,我们在控制台中看到“TyperError: Cannot read property 'length' of undefined”:

当我们点击“at eval”时,它会将我们带到这段特殊的 sn-p 代码,第 321 行突出显示:

我们似乎无法弄清楚导致该错误的原因。我们在数组 ($scope.data.list) 上使用 $watch 并且已经读到 $watchCollection 可能会更好,但我们尝试了没有任何改变。任何想法可能导致此错误以及如何摆脱它?

【问题讨论】:

  • 您的错误是说$scope.data.list 未定义,因此当您尝试使用未定义的.length 时,您会得到错误。如果您console.log($scope.data),您会看到什么?你怎么更新$scope.data.list
  • 只需检查数据,如果数据在您使用的地方,.length 不会出错。执行typeof 并检查数据。
  • 代码图片难以阅读,难以重现问题或复制到答案。

标签: angularjs undefined typeerror watch servicenow


【解决方案1】:

从您发布的代码中,您尚未定义或声明 $scope.data.list(我假设 $scope.data 是在某处定义的)。到 解决这个问题,你至少需要先声明你的$scope.data.list 来监视它。

来到$watch 部分,这取决于您的要求。 $scope.$watchCollection 查找在数组和元素中所做的更改,而, $scope.$watch 只会在数组完全为 分配给不同的人。否则,如果你想深入观看,你可以 将$scope.$watch 与作为第三个传递的布尔值true 变量一起使用 论据。

请参阅此链接以获取完整文档 - https://www.sitepoint.com/mastering-watch-angularjs/

【讨论】:

    【解决方案2】:

    据我所知,$scope.data.list 上的 $watch 在此集合中的任何值发生更改时都会调用

    因此,通过查看错误,$scope.data.list list 似乎不再在 $scope.data 中退出。尝试找出$scope.data 的变化。

    并使用下面的语法来监视集合

    $scope.$watchCollection('names', function(newList,oldList) {
       if(newList && newList.length) {
          $scope.data.list = newList.length;
       }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 2020-07-20
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多