Home > Mobile >  I'm Trying angular with filter rxjs, it's not filtering but displaying all portfolios
I'm Trying angular with filter rxjs, it's not filtering but displaying all portfolios

Time:05-29

I'm trying to implement the filter operator from rxjs, to filter out different portflios ALL | APP | WEB |API enter image description here

I expect the filter to filter out the portfolios according to the property type: enter image description here

Here is the filter implemmentation

Why does the click not filter portfolios here? what concept I'm I missing?

 portfolios: IPortfolio[] = [];
  portfolioType: 'all' | 'app' | 'web'|'api' = 'all';
  errorMessage = '';
  sub!: Subscription;
   ngOnInit(): void {
    this.sub = this.portFolioService.getPortfolioData().subscribe({
      next: portfolios => {
        this.portfolios = portfolios;
        filter((portfolio: IPortfolio) => portfolio.type === this.portfolioType);
      },
      error: err => this.errorMessage = err
    })
  }

and the view html has

<ul id="portfolio-filters">
  <li [class.filter-active]="portfolioType == 'all'" (click)="portfolioType = 'all'">All</li>
  <li [class.filter-active]="portfolioType == 'app'" (click)="portfolioType = 'app'">APP</li>
  <li [class.filter-active]="portfolioType == 'web'" (click)="portfolioType = 'web'">WEB</li>
  <li [class.filter-active]="portfolioType == 'api'" (click)="portfolioType = 'api'">API</li>
</ul>

CodePudding user response:

As your instance type IPortfolio[] is an array, you should use Array.prototype.filter to filter your portfolios:

 portfolios: IPortfolio[] = [];
  portfolioType: 'all' | 'app' | 'web'|'api' = 'all';
  errorMessage = '';
  sub!: Subscription;
   ngOnInit(): void {
    this.sub = this.portFolioService.getPortfolioData().subscribe({
      next: portfolios => {
        this.portfolios = portfolios.filter(portfolio => portfolio.type === this.portfolioType)
      },
      error: err => this.errorMessage = err
    })
  }

CodePudding user response:

You need to use a .pipe() where you can put a map to transform the portfolios with filter. Placing it as an expression inside the next callback will have no effect.

this.portfolioService.getPortfolioData().pipe(
  map(portfolios => portfolios.filter(portfolio => this.portfolioType === portfolio.type))
).subscribe(portfolios => {
  // portfolios are filtered now
})
  • Related