如何捕获子组件设置器抛出的错误?

时间:2020-08-14 07:23:42

标签: javascript angular typescript

我有一个App component,它存储通过Child component装饰器传递到@Input的值。

app.component.html

<app-child [myVariable]="myVariable"></app-child>

app.component.ts

@Component(...)
export class AppComponent implements OnInit {
  // First value, no error
  public myVariable = "Hello world";

  ngOnInit() {
    // After 1s set second value, no error
    setTimeout(() => {
      try {
        this.myVariable = "Cool message";
      } catch (e) {
        console.log("Error thrown");
      }
    }, 1000);

    // After 2s set third value, error from child setter is thrown but not catched
    setTimeout(() => {
      try {
        this.myVariable = null;
      } catch (e) {
        console.log("Error thrown");
      }
    }, 2000);
  }
}

@Input装饰器具有一个设置器,用于检查传递的值是否满足条件。如果不满足条件,将引发错误。

child.component.ts

@Component(...)
export class ChildComponent {
  private _myVariable: string;

  @Input()
  public set myVariable(val: string) {
    console.log('Trying to set value ' + val);
    
    if (!val) {
      throw new Error("Cannot set null value");
    }

    this._myVariable = val;
  }

  public get myVariable() {
    return this._myVariable;
  }
}

有什么方法可以捕获子@Input设置程序引发的错误吗?请通过示例检查StackBlitz

1 个答案:

答案 0 :(得分:2)

由于Input()的工作原理,我认为这是不可能的。您的分配只在父组件中分配了变量,而angular则以不同的方式处理输入更改。

解决此问题的一种方法是在父组件中引用您的孩子并直接设置属性。

我已使您的堆栈闪电使用了这种方法:https://stackblitz.com/edit/angular-ivy-drncnk