Angular 角度HttpClient方法不转换响应类型
刚开始使用新的HttpClient,但每当我调用时,都不会使用提供的类型强制转换响应。我尝试了一个接口和一个类。现在我假设您只能使用接口转换为响应,因为这是我们在文档中看到的唯一示例 我宁愿使用一个类在模型中有一些辅助函数。有没有办法做到这一点Angular 角度HttpClient方法不转换响应类型,angular,Angular,刚开始使用新的HttpClient,但每当我调用时,都不会使用提供的类型强制转换响应。我尝试了一个接口和一个类。现在我假设您只能使用接口转换为响应,因为这是我们在文档中看到的唯一示例 我宁愿使用一个类在模型中有一些辅助函数。有没有办法做到这一点 --component export class InvoicesComponent implements OnInit{ invoices; constructor(private invoiceService: InvoiceServic
--component
export class InvoicesComponent implements OnInit{
invoices;
constructor(private invoiceService: InvoiceService){}
ngOnInit() {
this.invoiceService.index()
.subscribe(
(invoices) => {
console.log(this.invoices);
}
);
}
--service class
export class InvoiceService {
constructor(private api :HttpClient) {}
index() {
return this.api.get<Array<Invoice>>('/invoices');
}
}
--interface
import { Customer } from "./Customer";
import { Payment } from "./Payment";
export interface IInvoice{
id: number;
user_id: number;
number: string;
cost: number;
status: number;
customer: Array<Customer>;
payments: Array<Payment>;
created_at: Date;
updated_at: Date;
deleted_at: Date;
}
--组件
导出类InvoicesComponent实现OnInit{
发票;
构造函数(私有invoiceService:invoiceService){}
恩戈尼尼特(){
this.invoiceService.index()
.订阅(
(发票)=>{
console.log(this.invoices);
}
);
}
--服务等级
出口类发票服务{
构造函数(私有api:HttpClient){}
索引(){
返回此.api.get('/invoices');
}
}
--接口
从“/Customer”导入{Customer};
从“/Payment”导入{Payment};
导出接口IInvoice{
id:编号;
用户id:号码;
编号:字符串;
成本:数量;
状态:编号;
客户:阵列;
支付:数组;
创建时间:日期;
更新日期:年月日;
删除日期:日期;
}
有没有办法做到这一点
HttpClient
无法知道如何为返回的数据实例化类。您需要自己执行此操作:
const invoices$ = this.http.get('/invoices')
.map(data => data.map(invoice => new Invoice(invoice)));
这假设您的Invoice
类有一个构造函数,该构造函数接受API端点返回的数据来创建实例
这里没有实际的»casting«。它在Typescript中被称为类型断言,因为它只影响类型信息。这可以通过以下简单示例看到:
const value1: any = 42;
const value2: string = value1 as string;
console.log(typeof value2); // 'number'
value2
将被(错误地)键入字符串,但它仍然是一个数字,对其调用字符串方法将使Typescript编译器感到高兴,但会在运行时导致错误。您可以通过如下继承来实现:
this.http.get<Invoice[]>(...)
.pipe(Invoice.serializeResponseMap());
很好!正如您所评论的,我知道我必须回到如何映射和克隆对象。我想我误解了目的。
export class Invoice extends SerializableMap {
static instanceType = Invoice;
...
constructor() { super(); }
...
}
class SerializableMap {
static instanceType: any;
static serializeResponseMap(): any {
const createInstance = (r) => {
return Object.assign(new this.instanceType(), r);
};
return map((respValue: any) => {
if (Array.isArray(respValue)) {
return respValue.map(r => createInstance(r));
}
return createInstance(respValue);
});
}
}