我有一个问题,我正在尝试将JSON响应分配给嵌套类型的类。
我使用的类型如下
摘要资源类:
export abstract class JBResource {
abstract type: string;
abstract header: string;
abstract info: string;
}
客户资源类:
import {JBResource} from './jbresource';
export class JBCustomer extends JBResource {
// Inherited variable
type = 'Customer';
get header(): string {
return this.name;
}
get info(): string {
return this.address1 + ', ' + this.postcode;
}
// Own variables
get id(): number {
return this.customerid;
}
customerid: number;
name: string;
address1: string;
address2: string;
address3: string;
address4: string;
postcode: string;
phone: string;
fax: string;
mobile: string;
email: string;
fromemail: string;
domain: string;
website: string;
}
API响应类:
import {JBResource} from './jbresource';
export class JBAPIResult<T extends JBResource> {
status: number;
error: string;
results: T[];
}
我想调用一个用结构化JSON响应的API,以及来自Angular HttpClient的类型化get请求,但结果是一个无类型的对象,而不是我期望的结果:
searchResults: JBCustomer[] = [];
constructor(private http: HttpClient) {
}
getCustomers() {
this.http.post<JBAPIResult<JBCustomer>>('/assets/customersService.php', {
action: 'search',
})
.subscribe(res => {
console.log('HTTP response', res);
this.searchResults = res.results;
console.log('Search Results', this.searchResults);
}, err => {
const sbRef = this.snackBar.open('Error getting customers', 'OK');
console.log('Alert Rule Fetch Error:', err);
}
);
}
从Chrome响应中可以看出,返回的对象不是APIResponse类型,只是一个简单的对象:
{status: 1, search: "%arta%", results: Array(1)}
results: Array(1)
0:
address1: "REDACTED, "
address2: "REDACTED, "
address3: "REDACTED, "
address4: "REDACTED"
customerid: "REDACTED"
email: "REDACTED"
fax: "REDACTED"
mobile: "REDACTED"
name: "REDACTED"
phone: "REDACTED"
postcode: "REDACTED"
__proto__ :Object
length: 1
__proto__: Array(0)
search: "%arta%"
status: 1
__proto__: Object
我从浏览之前的答案中了解到,应用HttpClient只会暴露类型为T的接口,以便您可以访问它们。
我如何让HttpClient将结果解析为我想要的类,所以我可以使用访问器方法。
如果没有实际的类型转换,使用HttpClient而不仅仅是HttpClient有什么意义,因为它实际上并没有改变响应对象的类型。