遇到错误后,更改检测似乎中断

Change detection appears to break after encountering error

本文关键字:检测 中断 错误 遇到      更新时间:2023-09-26

更新看来Angular团队有望解决这个问题。

https://github.com/angular/angular/issues/2413


我遇到了一个问题,Angular(Beta 15)的更改检测在遇到错误后似乎停止了工作——我不确定Zone是否在错误后取消订阅更改。

再现错误的最简单方法是尝试引用nullundefined的属性。

这个问题可以在这里看到。

@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和"elvis操作符"之外,有人经历过这种情况吗?

我认为这是按设计的。

如果您更改

{{dummy.myArray[0].text}}

{{dummy?.myArray[0].text}}

你不应该得到一个错误