Search code examples
angularangular5angular-httpclient

Angular HTTP get type check with nested interfaces


I was wondering if HttpClient get can type check nested interfaces.

For example I use GitHub API. If you check this request's: https://api.github.com/search/repositories?q=angular response you will see that the actual findings are in an array ('items').

So I want to extract the items array and also want to store the total_count.

I came up with this interface:

export interface Repository {
    name: string;
    full_name: string;
    size: string;
    forks_count: string;
    created_at: string;
    url: string;
    description: string;
    stargazers_count: string;
    open_issues_count: string;
}

and...

import { Repository } from "./repository.model";

export interface ReposirotySearchResponse {
    items: Repository[];
    total_count: number;
}

Based on ReposirotySearchResponse I want to extract the mentioned response with this:

return this._http.get<ReposirotySearchResponse>('https://api.github.com/search/repositories?q=angular');

But unfortunately angular doesn't resolve the response with the given type.

Do I miss something?


Solution

  • Duncan, http.get give you a complete response, so you must "map" the response if you want to get other response

    return this._http.get<ReposirotySearchResponse>('https://api.github.com/search/repositories?q=angular')
        .map((result:any)=>{
          console.log(result); //<--there the complete response
            return{
              total_count:result.total_count,
              items:result.items.map((item:any)=>{
                return {
                  name: item.name,
                  full_name: item.full_name,
                  size: item.size,
                  forks_count: item.forks_count,
                  created_at: item.created_at,
                  url: item.url,
                  description: item.description,
                  stargazers_count: item.stargazers_count,
                  open_issues_count: item.open_issues_count
                }
              })
            }
          })
    

    when you subscribe you receive only the fiels you want