Home > Back-end >  How to Display a List in Mat-Table without Duplicate?
How to Display a List in Mat-Table without Duplicate?

Time:12-09

So here's what i wanted to do. I have a list and i want to display it without duplicate. i tried the code of this set(this.model.map(x => x.map) but it wont work and got error anyone can fix it?

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
     
    });
  }
}

anyone can help me? i tried the different things. but same error

CodePudding user response:

You are trying to read this.model in the constructor, while this.model receives it's value in the asnychronous callback from getList in ngOnInit. At the point of construction there is no value assigned. Move the filter to the callback.

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)));
    }) 
  }

CodePudding user response:

I don't clearly understand your problem, but still trying to figure out.

You are removing duplicates from array before putting value in variable, you have to put that line after getting data from API, look at in my below code you can easily get it and I also optimize your code in better way.

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);
}

Try above code, Hope it may work for you.

Thanks!.

  • Related