【问题标题】:Angular4 router-outlet activate and ExpressionChangedAfterItHasBeenCheckedErrorAngular4 路由器出口激活和 ExpressionChangedAfterItHasBeenCheckedError
【发布时间】:2018-01-23 19:39:28
【问题描述】:

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

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

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

然后我将一个方法连接到router-outletactivate 属性,如下所示:

<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:表达式在检查后已更改。以前的值:'null'。当前值:'true'。

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

【问题讨论】:

    标签: angular


    【解决方案1】:

    你可以把你的一些逻辑放在 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);
          })
        }
    

    我希望这会奏效。

    【讨论】:

      猜你喜欢
      • 2018-07-27
      • 2018-02-02
      • 2020-12-29
      • 2018-05-29
      • 2017-12-07
      • 2018-05-09
      • 1970-01-01
      • 2018-01-19
      • 2019-07-16
      相关资源
      最近更新 更多