简体   繁体   English

如何初始化数组<t>在打字稿/角度?</t>

[英]How to initialize the Array<T> in typescript/angular?

I have an Angular 8 app.我有一个 Angular 8 应用程序。

Below is one of my models in typescript.下面是我在 typescript 中的模型之一。

export class Movie
{
  title:string;
  tickets: Array<Ticket>;
}

export class Ticket
{
   name:string;
   price:number;
}

In one of the components (movie), when I access the movie object, tickets is not getting initialized.在其中一个组件(电影)中,当我访问movie object 时, tickets没有被初始化。

movie.component.ts电影组件.ts

export class MovieComponent
{
  movieObj:Movie;

  constructor()
  {
    this.movieObj = new Movie();
    console.log(this.movieObj); // outputs title value but not tickets
   //console.log(this.movieObj.tickets[0].name); //undefined 
  }
}

While checking the Array type in TypeScript, it's an interface.在检查 TypeScript 中的 Array 类型时,它是一个接口。 (We cannot create an object of an interface) (我们不能创建一个接口的 object)

How to initialize the Array in typescript/angular?如何在打字稿/角度初始化数组?

Thanks!谢谢!

You can initialize it in the class itself.您可以在 class 本身中对其进行initialize

export class Movie
{
  title:string = 'Movie';
  tickets: Array<Ticket> = [{name: 'Ticket', price: 300}];
}

Stackblitz Demo Stackblitz 演示

You can do something like this.你可以做这样的事情。

export class Movie
{
  title:string = 'Movie';
  tickets: Ticket[] = [];
}
export class Ticket
{
   name:string;
   price:number;
}

If you want to do some logic while creating tickets, you have to use constructor of Movie class.如果你想在创建门票时做一些逻辑,你必须使用Movie class 的constructor函数。

You can initialize the property with an empty array of tickets using:您可以使用空的票证数组初始化属性:

export class Movie
{
  title:string;
  tickets: Ticket[] = [];
}

It doesn't matter using Ticket[] (shorthand syntax) or Array<Ticket> (generic syntax).使用Ticket[] (速记语法)或Array<Ticket> (通用语法)并不重要。 There isn't any semantic difference and they're completely equivalent.没有任何语义差异,它们是完全等价的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM