1
votes

I am trying filtering the return of HTTP request in Angular 7 using RXJS6.

I must filter the response; only get the Users with IdSkill equals to 1234.

However, I cannot achieve this. I just received this error:

Type 'Observable' is not assignable to type 'Observable>'. Type 'User[]' is missing the following properties from type 'Pagination': total, items

RXJS is not my strong skill; I just use the basics, only to do simple get/post HTTP requests.

My code:

/* 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))
    );
}

Thank you

2

2 Answers

1
votes

The operator you need would be a map, since you want to remap (filter) your inner result. RxJs filter is used when you want to filter the result itself that was emitted from Observable.

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)
      }))
    );
}
0
votes

Your endpoint returns what is returns so simply use find to get the single match out of it. Or filter to give you an array of matches.

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');

       });
}