How to get string[] array of unique item properties from Observable in angular2?

144 views Asked by At

I am getting an Observable. each item have ItemType. items.ItemType have duplicates like Electronics, Household, Electronics. I need a string array having unique ItemType and then select item from select box to display all items that belong to that type. I am new to angular so I apologize in advance.

item.service.ts

getAllItems():Observable<Item[]>{
  return this.http.get<Item[]>(this.url+'/AllItems');
}

item.component.ts

items: Observable<Item[]>;  

loadAllItems() {     
  this.items = this.itemService.getAllItems(); 
}  

item.component.html

 <mat-select  name="ItemType" > 
   <mat-option *ngFor="let item of items" [value]="item.ItemType">
   {{item.ItemType}}
   </mat-option>
</mat-select>
<table class="table" >
   <tr ngclass="btn-primary">
      <th class="tbl2">Name</th>
      <th class="tbl2"> ItemType</th>
      <th class="tbl2">Price</th>
   </tr>
   <tr *ngFor="let item of items">
      <td class="tbl2">{{item.Name}}</td>
      <td class="tbl2">{{item.ItemType}}</td>
      <td class="tbl2">{{item.ItemPrice}}</td>
</table>
1

There are 1 answers

0
Andrea Alhena On

You should operate directly in the service, applying the map operator against the Observable emitted value:

return this.http.get<Item[]>(this.url+'/AllItems').pipe(
    map(items => items.filter((item, idx) => a.findIndex(cmp => item.itemType === cmp.itemType) === idx))
);

The filter acts this way:

  • The item you are iterating on is searched with the findIndex method
  • If the position matches, it means that it's the first occurrency of the item
  • If the position doesn't match, it means that you are fetching an item that's present more than once

Check a quick test here: https://jsbin.com/keyitosiqu/edit?js,console