Angular HttpClient 方法不转换响应类型

2023-12-03

刚刚开始使用新的 HttpClient,但每当我拨打电话时,响应都不会使用提供的类型进行转换。我尝试了接口和类。现在我假设您只能使用接口来转换为响应,因为这是我们在文档中看到的唯一示例。

我宁愿使用一个类在模型中包含一些辅助函数。有没有办法以这种方式实现这一目标?

成分

export class InvoicesComponent implements OnInit{    
invoices;

constructor(private invoiceService: InvoiceService){}

ngOnInit() {
   this.invoiceService.index()
   .subscribe(
       (invoices) => {
           console.log(this.invoices);
       }
    );
}

服务等级

export class InvoiceService {
constructor(private api :HttpClient) {}   

  index() {
    return this.api.get<Array<Invoice>>('/invoices');
  }
}

界面

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;
}

有没有办法以这种方式实现这一目标?

HttpClient不知道如何为返回的数据实例化一个类。您需要自己执行此操作:

const invoices$ = this.http.get('/invoices')
  .map(data => data.map(invoice => new Invoice(invoice)));

这假设你的Invoice类有一个构造函数,它获取 API 端点返回的数据来创建实例。

这里并没有进行真正的“选角”。它在 Typescript 中称为类型断言,因为它只影响类型信息。这可以通过这个简单的例子看出:

const value1: any = 42;
const value2: string = value1 as string;
console.log(typeof value2); // 'number'

value2将被(错误地)键入为字符串,但它仍然是一个数字,并且在其上调用字符串方法将使 Typescript 编译器满意,但会在运行时导致错误。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular HttpClient 方法不转换响应类型 的相关文章

随机推荐