Filter array of objects in Angular4 without pipe

Men*_*Gil 1 arrays object typescript angular

I have an array of links that each element is an object that contain few strings - a link, description and category. I have different components that display the links, and I want in each component to display only the links of its category. So I want to filter the array by the category.

I have a mock-up array with all the links.

I try to filter the array of objects without a pipe. The reason why: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

Apparently the Angular team suggests to do the filtering in the component level and not using a pipe: "The Angular team and many experienced Angular developers strongly recommend moving filtering and sorting logic into the component itself."

So here's my component:

@Component({
    selector: 'startups',
    templateUrl: './startups.component.html'
})

export class StartupsComponent implements OnInit {

constructor(private appLinksService: DigitalCoinHubService) { }

title = 'Startups';


links: DCHlinks[]; // create a new array in type of DCHlinks to get the data

startupsLinks: DCHlinks [] = []; // will build the startsups links only 


getLinks(): void {
  this.links = this.appLinksService.getLinks(); // gets the array with the data from the service

  for (let i in this.links)
  {
     if (this.links[i].dchCategory == 'startups' )
     {
         this.startupsLinks[i].push(this.links[i]);
     }

  }

}

ngOnInit() {
    this.getLinks();   

}
Run Code Online (Sandbox Code Playgroud)

}

所以首先我从服务中获取大数组:

this.links = this.appLinksService.getLinks();
Run Code Online (Sandbox Code Playgroud)

然后我尝试构建一个仅包含相关链接的新数组。过滤器是按类别进行的。但是当我尝试通过推送其类别匹配的元素来构建新数组时 - 它给了我错误:

'DCHlinks' 类型不存在属性 'push'。

DCHlinks 是对象 - 这是类:

export class DCHlinks {
   dchLink: string;
   dchLinkTitle: string;
   dchLinkDescription: string;
   dchCategory: string;
 }
Run Code Online (Sandbox Code Playgroud)

知道如何做这个简单的过滤器吗?(和没有管道 - 见上面的原因..)

谢谢!

Saj*_*ran 5

您需要像之前一样初始化数组 startupsLinks

links: DCHlinks[] = [];
Run Code Online (Sandbox Code Playgroud)

或者你可以简单地使用 array.filter 来获取相关数据

this.startupsLinks = this.links.filter(t=>t.dchCategory == 'startups');
Run Code Online (Sandbox Code Playgroud)