角度过滤器 Observable 数组 [英] Angular filter Observable array

查看:33
本文介绍了角度过滤器 Observable 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Observable 数组,我想按名称过滤/查找项目.当我尝试使用过滤器选项时,它说

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

ProjectService.ts

import { Injectable } from '@angular/core';
import { Project } from "../classes/project";
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

import { Http } from '@angular/http';


@Injectable()
export class ProjectService {

  private projects: Observable<Project[]>;

  constructor(private http: Http) {
    this.loadFromServer();
  }

  getProjects(): Observable<Project[]> {
    return this.projects;
  }

  private loadFromServer() {
    this.projects = this.http.get('/api/projects').map(res => res.json());
  }

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


}

项目类

export class Project {
    public name: String;
    public miniDesc: String;
    public description: String;
    public category: String[];
    public images: any[];
}

推荐答案

应该是:

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

您误解了过滤器运算符.用于过滤从流返回的数据的运算符.您的流返回对象数组,因此您需要 filter array 来获取所需的值.

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;
    });
}

这篇关于角度过滤器 Observable 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆