我有一个Observable数组,我想按名称过滤/查找Project。当我尝试使用过滤器选项时,它说
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[];
}
答案 0 :(得分:33)
它应该是:
getProjectByName(name: String) {
return this.projects
.map(projects => projects.filter(proj => proj.name === name));
}
你误解了过滤器操作符。运算符用于过滤从流中返回的数据。您的流返回对象数组,因此您需要filter array
来获取所需的值。
上面的解决方案将在过滤后返回一个数组,如果您只想获得一个值,请使用以下解决方案
getProjectByName(name: String) {
return this.projects
.map(projects => {
let fl = projects.filter(proj => proj.name === name);
return (fl.length > 0) ? fl[0] : null;
});
}
答案 1 :(得分:0)
在角度7中,您不需要映射即可对订阅的值进行过滤
getProjectByName(name: String) {
return this.projects
filter(proj => proj.name === name));
}
答案 2 :(得分:-1)
在您的服务中,您可以定义<any>
类型或Project[]
类型以返回响应值,同样可以继续使用过滤器。例如<any>res.json()
或<Project[]>res.json()
并按照@Sajeetharan
的建议更新您的课程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(): Observable<any> {
this.projects = this.http.get('/api/projects').map((res: Response)=> <any>res.json());
}
getProjectByName(name: string) {
return this.projects.filter(proj => proj.name === name);
}
}
*始终在不在服务中的组件中编写过滤器,条件或操作。