首页 > 解决方案 > 从视图中删除重复值 - Angular

问题描述

下面是我想要过滤的重复字段,只显示一个而不是两个:

"release_dates":[ {" certificate":"PG-13","iso_639_1 ":"","note":"碲化物电影节","re​​lease_date":"2018-08-31T00:00:00.000Z", “类型”:1},

{"认证":"PG-13","iso_639_1" :"","note":"","re​​lease_date":"2018-09-28T00:00:00.000Z","type":2}]} ]}

下面的组件显示来自上述 json 的两条记录:

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';
import { MoviesService } from '../movies.service';

@Component({
  selector: 'app-movie',
  templateUrl: './movie.component.html',
  styleUrls: ['./movie.component.css']
})
export class MovieComponent implements OnInit {
  movie: Object;
  certification: Array<Object>;
  video: Object;
  constructor(
    private _moviesServices: MoviesService,
    private router: ActivatedRoute
  ) {

  }

  ngOnInit() {
    this.router.params.subscribe((params) => {
      const id = params['id'];
      this._moviesServices.getMovie(id).subscribe(movie => {
        this.movie = movie;
      });
      this._moviesServices.getCertification(id).subscribe((res: any) => {
        const usCertifications = res.results.filter((result: any) => {
          return result.iso_3166_1 === "US";
          // return this.certification === result.certificationAll;
        });
        this.certification = usCertifications;
      });

    })

  }

}

html:

<div class="mr-3" *ngIf="certification"><span *ngFor="let cert of certification">
          <span *ngFor="let release of cert.release_dates">
            <span class="badge badge-pill badge-warning" *ngIf="release.certification">{{release.certification}}</span>
          </span>
        </span>
      </div>

标签: angularangular6angular7angular8themoviedb-api

解决方案


您可以添加一个函数来删除组件中的重复项,或者使用管道做同样的事情类似于这个

result:any=[];
removeDuplicates(): any{
   this.certification.forEach((item)=>{
        if(this.result.indexOf(item) < 0) {
            this.result.push(item);
        }
   });
return this.result;
} 

然后在模板中调用它

<div class="mr-3" *ngIf="certification"><span *ngFor="let cert of removeDuplicates(certification)">
          <span *ngFor="let release of cert.release_dates">
            <span class="badge badge-pill badge-warning" *ngIf="release.certification">{{release.certification}}</span>
          </span>
        </span>
      </div>

推荐阅读