更新 看起来这个问题有望得到Angular团队的解决。
https://github.com/angular/angular/issues/2413
我遇到一个问题,即Angular(Beta 15)更改检测在遇到错误后似乎停止工作 - 我不确定Zone是否取消订阅错误后的更改。
重现错误的最简单方法是尝试引用null
或undefined
的属性。
可以看到问题here。
@Component({
selector: 'shell',
template: `
<h3>Shell</h3>
<p>{{dummy.myArray[0].text}}</p>
<button (click)="getUsers()">Get users!</button>
<button (click)="setDummyTextToNull()">Break stuff!</button>
<ul>
<li *ngFor="#user of users">{{user.login}}</li>
</ul>
`
})
export class ShellComponent implements OnInit {
public params;
public users;
public dummy;
constructor(private _router:Router,
public routeParams:RouteParams,
private _ghService:GithubService) {
this.params = this.routeParams;
this.subscribe();
}
ngOnInit() {
this.dummy = {
myArray: [
{ text: 'Some dummy text' }
]
};
}
setDummyTextToNull() {
this.dummy = null;
}
getUsers() {
this.getUsers();
}
subscribe() {
this._ghService.users$.subscribe(data => this.onResponse(data), err => {
console.warn('Could not fetch', err.status)
});
}
getUsers() {
this._ghService.loadUsers();
}
onResponse(data) {
console.log('Successfully fetched users', data);
this.users = this.shuffle(data);
}
shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
}
单击“获取用户”将获取github用户并随机播放列表。反复执行此操作可以查看正在使用的列表。强制模板引用null
属性后,更改检测似乎不再有效。
我期望的是,如果我点击该按钮会反复出现该错误,但实际上模板中的任何错误都会导致应用程序崩溃并需要刷新。
除了在任何地方使用ngIf
和“猫王操作员”之外,有没有人经历过这种情况并知道任何方式?
答案 0 :(得分:1)
我说这是按照设计的。
如果你改变了
{{dummy.myArray[0].text}}
到
{{dummy?.myArray[0].text}}
你不应该收到错误