Angular4 router-outlet activate和ExpressionChangedAfterItHasBeenCheckedError

时间:2018-01-23 11:18:36

标签: angular

我正在尝试更新某些按钮的状态。基本上有3个步骤(1,2和3)当在第一步时,所有步骤都被访问过。在步骤2中,访问了步骤1,在步骤3中,访问了步骤1和2,在结果页面上访问了所有步骤。

我创建了一个名为visited的对象:

export interface IVisited {
    one: boolean;
    two: boolean;
    three: boolean;
}

然后我将方法连接到router-outlet激活属性,如下所示:

<router-outlet (activate)="changeLinkState()"></router-outlet>

方法如下:

changeLinkState() {
  var url = this._router.url;
  if (!this.visited) {
    this.visited = {
      one: false,
      two: false,
      three: false
    };
  }
  switch (url) {
    case '/steps/one':
      this.visited.one = false;
      this.visited.two = false;
      this.visited.three = false;
      break;
    case '/steps/two':
      this.visited.one = true;
      this.visited.two = false;
      this.visited.three = false;
      break;
    case '/steps/three':
      this.visited.one = true;
      this.visited.two = true;
      this.visited.three = false;
      break;
    default:
      this.visited.one = true;
      this.visited.two = true;
      this.visited.three = true;
      break;
  }

  console.log(this.visited);
}

但是我收到了一个错误:

  

错误错误:ExpressionChangedAfterItHasBeenCheckedError:检查后表达式已更改。以前的值:&#39; null&#39;。当前价值:&#39; true&#39;。

有谁知道如何防止出现此错误?

1 个答案:

答案 0 :(得分:0)

你可以把一些逻辑放在setTimeout函数中 因为即

    changeLinkState() {
      var url = this._router.url;
      setTimeout(()=>{
      if (!this.visited) {
        this.visited = {
          one: false,
          two: false,
          three: false
        };
      }
      switch (url) {
        case '/steps/one':
          this.visited.one = false;
          this.visited.two = false;
          this.visited.three = false;
          break;
        case '/steps/two':
          this.visited.one = true;
          this.visited.two = false;
          this.visited.three = false;
          break;
        case '/steps/three':
          this.visited.one = true;
          this.visited.two = true;
          this.visited.three = false;
          break;
        default:
          this.visited.one = true;
          this.visited.two = true;
          this.visited.three = true;
          break;
      }

      console.log(this.visited);
      })
    }

我希望这会奏效。