Angular 4:从模型中捕获自定义错误的最佳实践

Angular 4: Best practices to catch custom error from model

我有一个 Angular4 应用程序,模型在输入数据时执行所有验证工作(如果输入错误,模型会抛出错误并且不设置变量),所以理想情况是 link 任何输入直接更改为与模型相关的设置方法,这将使组件非常精简和可扩展。 我的第一个策略是制定一个指令,我传递 setter 方法,我的指令执行 try/catch handle

我的 html 会是:

<div class="input-field col s12" appFormSetter [setFunction]="session?.getPlayer()?.setName">
   <i class="material-icons prefix">account_circle</i>
   <input #input placeholder="João da Silva" type="text" class="validate" 
          [ngModel]='session.getPlayer()?.getName()' name="name">
   <label for="first_name" class="active">Nome</label>
</div>

指令为:

import { Directive, HostListener, Input, ElementRef } from '@angular/core';
@Directive({
   selector: '[appFormSetter]'
})
export class FormSetterDirective {

  @Input() setFunction;

  @HostListener('input') onInput() {
    try {
        this.setFunction(this.elRef.nativeElement.value);
    } catch (error) {
        // Would catch the error and show in some <small>
        console.log('Error', error);
    }
  }

  constructor(private elRef: ElementRef) {
    console.log('mychildren', this.inputElement);
  }
}

模型将是:

public setName(name: string): void {
    if(!isValid()) throw 'myError';
    this.name = name;
}

处理此类问题的最佳做法是什么? 我可以不通过指令直接通过 html 获取错误吗?

你应该使用 ReactiveFormsModule。它具有更改检测和验证处理功能。
我给出了一个涉及 cookie 的答案,这是一个用于必需验证的模板 here
下载示例,体验一下实际示例。

如果将鼠标悬停在 link 上,您会看到 link 中有 'final'。另一个你必须通过并手动添加代码。我建议使用 'final' 版本。

另外如果你去 Angular.io and search on "validator" you'll be able to find examples of things like EmailValidator, PatternValidator. Here's the main Validators class.

如果你想了解更多Angular大学有很好的课程。
他们有一个 YouTube 频道,他们的代码在 Github.
上 您需要确定要查看哪些分支以及视频:
Rxjs and Reactive Patterns Angular Architecture Course”。