我正在调用服务并返回一个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')
);
答案 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));
}
}
几条评论:
mergeMap()
运算符。它允许我展平 API返回的用户数组,并让每个用户在observable中作为单个值发布。我这样做了所以我可以用其他RxJS操作符单独操作(和过滤)每个用户,而不必处理一组用户。