我正在处理用户-角色关系,我的代码可以正常工作,只是它在 Angular 端产生了一个无限的摘要错误,我认为这对性能有一些影响。在我的用户类(ES2015)中,我有:
get roles() {
return Roles.findByIds(this._roleIds).fetch()
}
问题是上面的getter每次都返回一个新对象,所以在Angular看来,它们是不相等的。我试过track by
了,如下:
<ul>
<li ng-repeat="role in user.roles track by role._id">
{{role.name}}
</li>
</ul>
引发以下异常:
Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [[{"msg":"fn: regularInterceptedExpression","newVal":20,"oldVal":19}],[{"msg":"fn: regularInterceptedExpression","newVal":21,"oldVal":20}],[{"msg":"fn: regularInterceptedExpression","newVal":22,"oldVal":21}],[{"msg":"fn: regularInterceptedExpression","newVal":23,"oldVal":22}],[{"msg":"fn: regularInterceptedExpression","newVal":24,"oldVal":23}]]
没有track by
,我看到更长的堆栈跟踪,提到“管理员”
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [[{"msg":"fn: regularInterceptedExpression","newVal":9,"oldVal":8},{"msg":"fn: regularInterceptedExpression","newVal":"Administrator"}],[{"msg":"fn: regularInterceptedExpression","newVal":10,"oldVal":9},{"msg":"fn: regularInterceptedExpression","newVal":"Administrator"}],[{"msg":"fn: regularInterceptedExpression","newVal":11,"oldVal":10},{"msg":"fn: regularInterceptedExpression","newVal":"Administrator"}],[{"msg":"fn: regularInterceptedExpression","newVal":12,"oldVal":11},{"msg":"fn: regularInterceptedExpression","newVal":"Administrator"}],[{"msg":"fn: regularInterceptedExpression","newVal":13,"oldVal":12},{"msg":"fn: regularInterceptedExpression","newVal":"Administrator"}]]
所以现在,我的选择是避免使用 getter,并使用如下updateRoles
方法:
updateRoles() {
this.roles = Roles.findByIds(this._roleIds).fetch()
}
这消除了异常,但似乎updateRoles
每次_roleIds
数组更改时我都必须手动调用。我只是想知道与我上面提到的方法相比是否有更好的方法。