Home > Back-end >  Angular error - Type 'Response' is not generic
Angular error - Type 'Response' is not generic

Time:09-10

I am trying to get a nested array from an http response using Angular 14

getItems(): Observable<Item[]>
{
    return this._httpClient.get<Item[]>(this.apiUrl   'items').pipe(
        tap((items) => {
            this._items.next(items);
        })
    ).pipe(
        map((res: Response<Item[]>) => {
            res = res.array1;
            return res;
        })
    );
}

but get error on

Response<Item[]>

saying:

Type 'Response' is not generic.ts(2315)

How can I solve this ?

CodePudding user response:

The type provided to the http.get<T>() call is not correct. It should match the shape returned by your api. So if your response shape looks like this:

interface GetItemsResponse {
   array1: Item[]
}

Then you should indicate that type on your get call:

getItems(): Observable<Item[]>
{
    return this._httpClient.get<GetItemsResponse>(this.apiUrl   'items').pipe(
        map((res: GetItemsResponse) => res.array1),
        tap((items: Items[]) =>  this._items.next(items))
    );
}

Also, you don't need to specify the types in the operators, typescript will correctly infer them:

getItems(): Observable<Item[]>
{
    return this._httpClient.get<GetItemsResponse>(this.apiUrl   'items').pipe(
        map(res => res.array1),                // res is type GetItemsResponse
        tap(items =>  this._items.next(items)) // items is type Item[]
    );
}
  • Related