1

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 Answers 2

1

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)
      }))
    );
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hmm... while this is true and needed for correct functionality, this may not be the entire picture as x.items.filter returns a truthy value and allows the code to work. The type error seems be elsewhere
That looks like JavaScript's filter not RxJS's. But Map looks helpful here.
0

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

       });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.