Angular filter Observable array

前端 未结 2 467
情书的邮戳
情书的邮戳 2020-12-29 02:15

I have an Observable array and I want to filter/find the Project by name. When I try to use the filter option it is saying

ProjectService.ts



        
2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-29 03:13

    it should be:

    getProjectByName(name: String) {
      return this.projects
        .map(projects => projects.filter(proj => proj.name === name));
    }
    

    you misunderstood about filter operator. The operator using to filter data return from stream. Your stream return array of object, so you need filter array to get you needed value.

    The solution above will return an array after filtered, if you wanna get only one value, using following solution

    getProjectByName(name: String) {
      return this.projects
        .map(projects => {
          let fl = projects.filter(proj => proj.name === name);
          return (fl.length > 0) ? fl[0] : null;
        });
    }
    

提交回复
热议问题