显示在 Angular 的一段时间内生成的选定错误消息

Displaying selected error messages that get generated over a period of time in Angular

我想在消息生成时显示消息。我只想显示我创建的错误数组中选定的错误消息。我正在使用 array.filter 方法来过滤错误消息,但这不起作用。它只是显示数组中的所有元素。

这是服务代码:

error: any[] = [];

addError() {
    // error gets generated over a period of time
    this.error.push({ msg: 'A', statusText: 'a', status: 25 });
    this.error.push({ msg: 'B', statusText: 'b', status: 35 });
    this.error.push({ msg: 'C', statusText: 'c', status: 45 });
    this.error.push({ msg: 'D', statusText: 'd', status: 55 });
    this.error.push({ msg: 'E', statusText: 'e', status: 65 });
    this.error.push({ msg: 'F', statusText: 'f', status: 75 });

    this.error = this.error.filter(err => err.status > 45);
  }

  getErrors(): any[] {
    console.log(`in the get methog ${JSON.stringify(this.error)}`);
    return this.error;
  }

这是显示错误消息的 parent-component

  data: any[];

  constructor(private _error: ErrorService) {}

  ngOnInit() {
    this.data = this._error.getErrors();
  }

这里是产生错误的child-component

addError() {
    this._info.addInfo();
  }

注意:这个addError方法在按钮的点击事件上被调用。

这里的问题是:即使我正在过滤错误数组,我也可以看到所有错误消息(A-F) 而我应该只看到 D, E and F.

我哪里错了??我是否需要使用 observable 来实现预期的结果,或者我可以通过对上述代码进行一些修改来实现?

这是 link 到 stackblitz

问题出在参考文献上。

  • ngOnInit of parent-component data 持有 error 数组的引用。
  • 当我们执行 array.filter() 时,error 将保留一个新引用但不会在 parent-component 中更新。

解决方案 我们可以在不使用 Observable 的情况下通过简单修改代码来修复。我们可以使用 Observable 来解决这个问题。

第一步:ErrorService.

中添加filteredErrors属性reader
@Injectable({
  providedIn: 'root'
})
export class ErrorService {

  error: any[] = [];

  addError() {
      this.error.push({ msg: 'A', statusText: 'a', status: 25 });
      this.error.push({ msg: 'B', statusText: 'b', status: 35 });
      this.error.push({ msg: 'C', statusText: 'c', status: 45 });
      this.error.push({ msg: 'D', statusText: 'd', status: 55 });
      this.error.push({ msg: 'E', statusText: 'e', status: 65 });
      this.error.push({ msg: 'F', statusText: 'f', status: 75 });
  }

  get filteredErrors() {
    return this.error.filter(err => err.status > 45);
  }
}

第 2 步: 阅读 filteredErrors 以了解迭代过滤后的错误。以下是 ParentComponent.

的详细信息
@Component({
  selector: 'app-parent',
  template: `<p *ngFor="let error of errors">
      First Name: {{ error.msg }} Last Name: {{ error.statusText }}
    </p>
    <app-child></app-child>`
})
export class ParentComponent {

  constructor(public  _error: ErrorService) {}

  get errors() {
    return this._error.filteredErrors || [];
  }
}

为了参考添加了 stackblitz 代码 link。