简体   繁体   English

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

[英]How to catch an error thrown by a child component setter?

I have an App component which stores a value that is passed into a Child component via an @Input decorator.我有一个App component ,它存储一个通过@Input装饰器传递给Child component的值。

app.component.html app.component.html

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

app.component.ts 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);
  }
}

The @Input decorator has a setter to check whenever the passed value meets a condition. @Input装饰器有一个设置器来检查传递的值何时满足条件。 If the condition is not met, an error will be thrown.如果不满足条件,则会抛出错误。

child.component.ts 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;
  }
}

Is there any way how can I catch the error thrown by the child @Input setter?有什么办法可以捕获子@Input setter 抛出的错误? Please check the StackBlitz with an example.请通过示例检查StackBlitz

I believe this is not possible because of how Input() works.我相信这是不可能的,因为Input()是如何工作的。 Your assignment only assigns the variable in your parent component, but angular handles the input changes differently.您的分配仅分配父组件中的变量,但 angular 以不同方式处理输入更改。

One way to solve this is to reference your child in your parent component and set the property directly.解决此问题的一种方法是在父组件中引用您的孩子并直接设置属性。

I've forked your stackblitz to use this approach: https://stackblitz.com/edit/angular-ivy-drncnk我已经分叉了你的 stackblitz 以使用这种方法: https://stackblitz.com/edit/angular-ivy-drncnk

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM