在Typescript中使用地图

4

我在使用Typescript制作地图时遇到了一些问题。我的目标是使用类似于Java中的HashMap的数据结构。以下是我的Java对象示例:

public class Payment {
    private String id;
    private DateTime created;

    //when they actually received the payment
    private DateTime paidDate;
    private String customerId;
    private String companyId;
    private BigDecimal amount;
    private BigDecimal allocated;
    private String description;

    // it must be the Id of PaymentMethod
    private String type;

    //to improve it
    private String currency;

    private Boolean fullPaid = false;
    private Boolean lockArchive = false;

    //<InvoiceId, Amount>
    private HashMap<String, BigDecimal> invoices = new HashMap<>();

    //getter and setters....

所以我在Typescript中所做的是创建一个类似的类,例如:
export class Payment {
  public id?:string;
  public created?:string;
  public paid_date?:Date;
  public customer_id?:string;
  public company_id?:string;
  public amount?:number;
  public allocated?:number;
  public description?:string;
  public type?:string;
  public currency?:string;
  public full_paid?:boolean;
  public lock_archive?:boolean;
  public invoices:  {[invoice_id:string]:number};


  constructor(id: string, created: string, paid_date: Date, customer_id: string, company_id: string, amount: number, allocated: number, description: string, type: string, currency: string, full_paid: boolean, lock_archive: boolean, invoices: { [p: string]: number }) {
    this.id = id;
    this.created = created;
    this.paid_date = paid_date;
    this.customer_id = customer_id;
    this.company_id = company_id;
    this.amount = amount;
    this.allocated = allocated;
    this.description = description;
    this.type = type;
    this.currency = currency;
    this.full_paid = full_paid;
    this.lock_archive = lock_archive;
    this.invoices = invoices;
  }
}

我正在尝试向发票映射中添加内容,因此我有以下函数:

  public invoicesMap = new Map<string, number>();

  constructor(public dialogRef: MdDialogRef<PaymentInvoiceSelectDialogComponent>,
              private customerService:CustomerService,
              private paymentServices: PaymentsService) {

  }

  ngOnInit() {

    this.customer.subscribe((res)=>{
      this.customer_name = res.customer_name
    }, error=>{
      console.error(<any>error);
    });

    this.customerService.getListOfCustomerInvoices(this.customerId,'0','25')
      .subscribe( (res) =>{
       this.invoices = res;
      },
      error => {
        console.error(<any>error);
      });

  }

  selectedInvoice(invoiceId: string, amount: number, event:any) {

    if(event.checked){

      if(!_.isEmpty(this.payment.invoices)){

        for(let [key, value] of this.invoicesMap) {

          if (key !== invoiceId) {

            this.invoicesMap.set(invoiceId, amount);

            for(let [key, vvalue] of this.invoicesMap) {

              if (key === invoiceId) {

                this.availableAllocation = this.availableAllocation - vvalue;

              }
            }
          }
        }
      } else {

        this.invoicesMap.set(invoiceId,amount);

        for(let [key, vvalue] of this.invoicesMap) {
          if(key === invoiceId){
            this.availableAllocation = this.amount - vvalue;
          }
        }
      }
    } else if(!event.checked){

      for(let [key, vvalue] of this.invoicesMap) {

        if (key === invoiceId) {

          console.log("removing an item");
          this.availableAllocation += vvalue;
        }

      }
    }

    //at this point I would like to set this.payment.invoices to this.invoiceMap
    for(let [key, value] of this.invoicesMap){
      let v = {invoice_id:key,amount:value};
      console.log(v);
    }

    this.payment.allocated = this.availableAllocation;
  }


  savePayment(){
    console.log(JSON.stringify(this.payment));
    // this.paymentServices.updatePayment(this.payment)
    //   .subscribe((res)=>{
    //     this.payment = res;
    //     this.dialogRef.close(this.payment);
    //     },
    //     error =>{
    //       console.log(<any>error);
    //     });
  }

项目已添加到invoiceMap,但我现在遇到的问题是将invoiceMap添加到payment.invoices中。如果有人能指点一下方向,将不胜感激。谢谢。

4个回答

5
你也可以将其更改为 Payment 中的 Map:
public invoices: Map<string, number>;

然后你只需要简单地指定你拥有的地图即可。
或者你可以遍历地图条目并将它们转换为像Payment中一样的对象:

let m = new Map<string, number>();

let m2 = {} as { [key: string]: number };
m.forEach((value, key) => m2[key] = value);

我已将发票更改为付款映射,就像您所说的那样迭代映射,它按预期工作。感谢您的帮助。 - Limpep

2
如果您要使用字符串作为键,则没有理由使用哈希映射,因为JavaScript和TypeScript中的每个对象都是简单的映射。您需要使用Map类的唯一原因是如果您需要除String以外的其他东西作为键。
请看一下这个问题 -> JavaScript哈希映射是如何实现的?

1

最简单的方法是使用 Record 类型 Record<string, any>

const invoicesMap : Record<string, any> 

这将允许您拥有任何字符串和值的类型。仅在事先不知道键时使用它。

您还可以查看Partial类型。如果您有一些值但不是全部。

https://www.typescriptlang.org/docs/handbook/utility-types.html


0
如果我理解你的意思,你可以使用TypeLite:http://type.litesolutions.net/ 这个插件可以将任何C#类转换为TypeScript类。
在异步通信之前,你需要将请求解析为json格式,并在后台代码(或控制器)中将对象序列化为json格式进行响应。

谢谢,但我正在使用Java,而且我可以使用这个https://github.com/vojtechhabarta/typescript-generator。 - Limpep

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接