Angular 使用嵌套接口的 HTTP get 类型检查
Angular HTTP get type check with nested interfaces
我想知道 HttpClient get 是否可以类型检查嵌套接口。
例如我使用GitHubAPI。如果您检查此请求的:
https://api.github.com/search/repositories?q=angular
响应你会看到实际的发现在一个数组中('items')。
所以我想提取 items 数组并且还想存储 total_count.
我想到了这个界面:
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;
}
和...
import { Repository } from "./repository.model";
export interface ReposirotySearchResponse {
items: Repository[];
total_count: number;
}
基于 ReposirotySearchResponse 我想提取上述回复:
return this._http.get<ReposirotySearchResponse>('https://api.github.com/search/repositories?q=angular');
但遗憾的是 angular 无法解析给定类型的响应。
我错过了什么吗?
Duncan,http.get给你一个完整的回复,所以你必须"map"回复如果你想得到其他回复
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
}
})
}
})
当您订阅时,您只会收到您想要的字段
我想知道 HttpClient get 是否可以类型检查嵌套接口。
例如我使用GitHubAPI。如果您检查此请求的: https://api.github.com/search/repositories?q=angular 响应你会看到实际的发现在一个数组中('items')。
所以我想提取 items 数组并且还想存储 total_count.
我想到了这个界面:
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;
}
和...
import { Repository } from "./repository.model";
export interface ReposirotySearchResponse {
items: Repository[];
total_count: number;
}
基于 ReposirotySearchResponse 我想提取上述回复:
return this._http.get<ReposirotySearchResponse>('https://api.github.com/search/repositories?q=angular');
但遗憾的是 angular 无法解析给定类型的响应。
我错过了什么吗?
Duncan,http.get给你一个完整的回复,所以你必须"map"回复如果你想得到其他回复
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
}
})
}
})
当您订阅时,您只会收到您想要的字段