Filtering array with RXJS
我正在尝试使用RXJS6在Angular 7中过滤HTTP请求的返回。
我必须过滤响应;仅获得具有等于1234的IdSkill的用户。
但是,我无法实现这一目标。我刚收到此错误:
类型"可观察"不能分配给类型"可观察>"。
类型"用户[]"缺少类型"分页"中的以下属性:总计,项目
RXJS不是我的强项。我只是使用基础知识,仅用于执行简单的获取/发布HTTP请求。
我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | /* Interface */ export interface Pagination< T > { total: number; items: t[]; } export interface User { idUser: number; name: string; active: boolean; skill: Skill; } export interface Skill { idSkill: number; name: string; } /* Service */ getUsers(): Observable<Pagination<User>> { return this._httpClient.get<Pagination<User>>( 'http://localhost/api/users', { headers: this._auth } ).pipe( filter(x => x.items.filter(user => user.skill.idSkill == 1234)) ); } |
谢谢
您需要的运算符将是
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import { map } from 'rxjs/operators'; /* Service */ getUsers(): Observable<Pagination<User>> { return this._httpClient.get<Pagination<User>>( 'http://localhost/api/users', { headers: this._auth } ).pipe( map((pagination: Pagination<User>) => ({ ...pagination, items: pagination.items.filter(user => user.skill.idSkill == 1234) })) ); } |
您的端点返回的是返回值,因此只需使用
1 2 3 4 5 6 7 8 9 10 11 12 13 | getUsers(): Observable<Pagination<User>> { return this._httpClient.get<Pagination<User>>(url,{ headers: this._auth }) .pipe(take(1)) .subscribe(users => { // finds a single result theObject = users.find(obj => obj.IdSkill == 5); // return an array of all matching results arrayOfResults = data.filter(obj => obj.IdSkill === 'JavaSc'); }); } |