出现错误时未通知子组件

Child Component is not being notify when there are errors

我在两个组件之间使用 angular parent/child 通信,我能够从子组件获取父组件在 onChanges 生命周期中所做的更改,但是问题是当出现错误时,更改不会应用于子组件。

家长:

confirm() {
      this.someService.saveSomthing(someObject).subscribe(data => {
        if (data === 1) {
          this.showConfirmation = false;   <--- child is being notified 
          this.alertService.showMessage('success');
        }
      }, error => {
          this.showConfirmation = true;   <--- child is not being notified
        this.alertService.showMessage(
          'Validation Error'
          );
        });
  }

有更好的系统来通知 child,您可以尝试使用 EventEmitter 并根据需要发出 true 或 false。这样,您可以多次发出 false 并且它会在不触发所有组件树中的更改检测的情况下工作:

// parent.ts
showConfirmationEvent = new EventEmitter<boolean>();

...
error => {
  this.showConfirmationEvent.emit(false);
} 

// parent.html

<child [showConfirmationEvent]="showConfirmationEvent">

// child.ts

@Input() showConfirmationEvent: EventEmitter<boolean>;

...

ngOnInit() {
   this.showConfirmationEvent.subscribe(value => {
     // use your boolean
   });
}