Angular2 在服务内部应用过滤器

Angular2 apply filter inside service

我正在使用 Angular 2 构建应用程序。我有一个 服务 ,我试图在从服务获取数据之前 过滤数据 。我想要一个函数,我可以只 询问一个项目元素而不是整个数组

这是我试过的代码,但这种方法不起作用:

getProject(id: number): Observable<Project> {
        return this.http.get(this.url).map(this.extractData).filter(project => (<Project>project).id == id).catch(this.handleError2);

    // return this.getProjects().filter(project => project.id === id);
    //return this.http.get(this.url).toPromise().then(x => x.json().data.filter(project => project.id === id)[0]).catch(this.handleError);
}

private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
}

private handleError2 (error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    let errMsg = (error.message) ? error.message :
    error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
}

最好从您调用服务的地方过滤组件中的数据。

所以你的服务就像:

getProject(id: number): Observable<Project> {
  return this.http.get(this.url).map(this.extractData);
}
private extractData(res: Response) {
  let body = res.json();
  return body.data || []; // return value must be array to use filter function in component
}

在您的组件中,您可以执行以下操作:

service.getProject(projectId).subscribe((res) => {
  let filtered = [];
  if(res.length){
    filtered = res.filter((item) => {
      return item.id === projectId;
    });
  }
});

如果这部分代码有效:

getProjects() {
        return this.http.get(this.url).map(this.extractData).catch(this.handleError2);
     }

然后你可以调用单个项目:

getProject(id: number) {
        return this.getProjects()
            .then(projects => projects.filter(project => (<Project>project).id == id);
    }

对我来说,您似乎在混合使用同步代码和异步代码,return 不是那样工作的。您可以 return 属性稍后更改的对象(函数)(也称为 Promise)

我怀疑http.get()是否提供了一个数组供您映射


.toPromise() 看起来像是 hack,但你应该 return Promise 链


return this.http.get(this.url).then(data => data.map(this.extractData).filter(project => (<Project>project).id == id).catch(this.handleError2));

如果this.http.get()不是return一个Promise,而是接受一个回调,你可以构造一个:

return new Promise (resolve => this.http.get(this.url, resolve)).then(data => data.map(this.extractData).filter(project => (<Project>project).id == id).catch(this.handleError2));

无论调用什么 getProject() 都可以与 getProject().then()

链接