【问题标题】:How to Display a List in Mat-Table without Duplicate?如何在 Mat-Table 中不重复显示列表?
【发布时间】:2022-12-09 17:09:01
【问题描述】:

所以这就是我想做的。我有一个列表,我想不重复地显示它。 我尝试了这个集合的代码(this.model.map(x => x.map)但是它不会工作并且出现错误任何人都可以修复它吗?

model: myModel[];
myObj:any;
result:[];

constructor(){
this.result = Array.from(new Set(this.model.map(x => x.Name))); <----- i got the error of this one 
`Cannot read properties of undefined (reading 'map')`
}

ngOninit(){
this.getList()

getList() {
    this.services.getListAll(5, 1).subscribe((data: myModel[]) => {
      this.myObj= data;
      this.model= this.myObj.items
    }) 
  }
  onPaginateChange(event: PageEvent ){
    let index = event.pageIndex;
    let size = event.pageSize;
    index = index + 1;

    this.services.getListAll(size, index).pipe(first()).subscribe((data: myModel[]) => {
      this.myObj= data;
      this.model= this.myObj.items
     
    });
  }
}

任何人都可以帮助我吗?我尝试了不同的东西。但同样的错误

【问题讨论】:

  • myModel 的类型定义是什么?您什么时候认为该类型的两个实例是彼此重复的?

标签: angular typescript rxjs


【解决方案1】:

您正在尝试在构造函数中读取 this.model,而 this.model 从 ngOnInit 中的 getList 的异步回调中接收它的值。在构建时没有分配任何值。将过滤器移至回调。

getList() {
    this.services.getListAll(5, 1).subscribe((data: myModel[]) => {
      this.myObj= data;
      this.model= this.myObj.items
      this.result = Array.from(new Set(this.model.map(x => x.Name)));
    }) 
  }

【讨论】:

    【解决方案2】:

    我不太清楚你的问题,但仍在努力弄清楚。

    您在将值放入变量之前从数组中删除重复项,您必须在从 API 获取数据后放置该行,在我下面的代码中查看您可以轻松获取它并且我还以更好的方式优化您的代码。

    public model: myModel[];
    public myObj: any = null;
    public result: [] = [];
    
    ngOninit(){
      this.getList(5, 1); // Optional to pass parameter
    }
    
    public getList(pageSize: number = 5, pageNumber: number = 1) {
        this.services.getListAll(pageSize, pageNumber).subscribe((data: myModel[]) => {
          this.myObj= data;
          this.model= this.myObj?.items || [];
          this.result = [];
          if (this.model != null && this.model.length > 0) {
            this.result = Array.from(new Set(this.model.map(x => x.Name)));
          }
        }) 
      }
    }
    
    public onPaginateChange(event: PageEvent ){
       let index = event.pageIndex;
       let size = event.pageSize;
    
       this.getList(size, index + 1);
    }

    试试上面的代码,希望它对你有用。

    谢谢!。

    【讨论】:

      猜你喜欢
      • 2020-11-20
      • 2021-12-29
      • 2021-02-25
      • 2019-05-20
      • 1970-01-01
      • 2020-11-12
      • 1970-01-01
      • 2021-05-27
      • 1970-01-01
      相关资源
      最近更新 更多