1

I'm querying an API and trying to get a specific element out of the array it returns.

I query the API and get a JSON response back. I send the response via a .map call to a function that maps each object in the response to a T.

getOne(num: number): Observable<T> {
      let t$ = this.http
      .get(`${this.API_URL}?${this.getParams()}`)
        .map(mapToTypeT)
        .filter(x => Number.parseInt(x.rn) === num)

      return t$;
}

I want to call filter to find the one element that has a value rn that matches the num parameter. I know that's not right, as I'm getting two errors back:

Property 'rn' does not exist on type 'T[]'

Type 'T[]' is not assignable to type 'T'

Is there a way I can reach into the T[ ] array to check the properties of each element, and then return the element that matches the given predicate? As it stands I'm working with an Observable array of T's but I want to return an Observable of just one T.

For reference, the other two functions:

function mapToTypeT(response:Response): T[]{
  return response.json().map(t => toT(t))
  }


  function toT(r:any): T{
  let t = <T>({
    staId:    r.staId,
    stpId:    r.stpId,
    staNm:    r.staNm,
    stpDe:    r.stpDe,
    rn:       r.rn,
  });
  return t;
}
0

1 Answer 1

0

I see something wrong here.

  • Return type should be:

Observable<Array<T>>

  • Add 'any' into filter function:

.filter(x => Number.parseInt((<any>x).rn) === num)

Sign up to request clarification or add additional context in comments.

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.