angular2,RxJs过滤可观察到的结果?

时间:2017-02-13 11:08:15

标签: angular ecmascript-6 rxjs rxjs5

我正在调用服务并返回一个json对象。我想过滤结果,但似乎无法让它发挥作用。请求工作正常,我使用过滤器函数传递关键字。我试图控制登录它,但它返回一个空数组。

提前感谢。

 let keywords = 'defunkt';

this.http.get('https://api.github.com/users')
  .map((res: Response) => res.json())
  .subscribe(
    data => {
      this.result = data,
        console.log(this.result.filter((keyword, index) => keywords.lastIndexOf(keyword) === index));
    },
    err => console.error(err),
    () => console.log('done')
  );

1 个答案:

答案 0 :(得分:0)

这是一项服务,可让您通过登录搜索Github用户:

@Injectable()
export class GithubSearchService {

  constructor(private http: Http) { }

  byLogin(query: string): Observable<any> {
    return this.http.get('https://api.github.com/users')
      .map(resp => resp.json())
      .mergeMap(val => val)  // <!-- this is important
      .filter((user: any) => user.login.includes(query));
  }

}

现在使用此服务的代码:

export class AppComponent {

  constructor(private search: GithubSearchService) { }

  ngOnInit() {
    this.search.byLogin('van')
      .subscribe(results => console.log(results));
  }

}

几条评论:

  • 在此实施中,过滤在客户端上完成。这意味着您不会通过所有Github用户进行搜索,而只能通过API调用返回的用户进行搜索(默认情况下为30个用户)。 Github API可能接受允许您在服务器上进行过滤的参数。
  • 请注意使用mergeMap()运算符。它允许我展平 API返回的用户数组,并让每个用户在observable中作为单个值发布。我这样做了所以我可以用其他RxJS操作符单独操作(和过滤)每个用户,而不必处理一组用户。
  • 我使用String.prototype.includes()检查用户的登录是否包含给定的搜索查询(区分大小写的搜索)。由于这部分是纯JS,因此您可以轻松地根据其他标准对其进行过滤。