Angular filter Observable array

前端 未结 2 474
情书的邮戳
情书的邮戳 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:07

    In your Service you can define type or Project[] type to return the response value and same could be continue with filter. e.g. res.json() or res.json()

    and also update your class as suggested by @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;
    
      constructor(private http: Http) {
        this.loadFromServer();
      }
    
      getProjects(): Observable {
        return this.projects;
      }
    
      private  loadFromServer(): Observable {
        this.projects = this.http.get('/api/projects').map((res: Response)=> res.json());
      }
    
      getProjectByName(name: string) {
        return this.projects.filter(proj => proj.name === name);
      }   
    }
    

    *always write your filters, conditions or manipulation in component not in services.

提交回复
热议问题