The*_*eal 34 arrays typescript angular
我有以下表达式:
public mySentences:Array<string> = [
{id: 1, text: 'Sentence 1'},
{id: 2, text: 'Sentence 2'},
{id: 3, text: 'Sentence 3'},
{id: 4, text: 'Sentenc4 '},
];
Run Code Online (Sandbox Code Playgroud)
这是行不通的,因为我的数组不是类型string而是包含对象列表.我如何delcare我的数组包含一个对象列表?
*没有一个新的组件宣布一个似乎浪费的句子类
mar*_*tin 73
我假设你正在使用打字稿.
要格外小心,您可以将您定义type为需要匹配特定接口的对象数组:
type MyArrayType = Array<{id: number, text: string}>;
const arr: MyArrayType = [
{id: 1, text: 'Sentence 1'},
{id: 2, text: 'Sentence 2'},
{id: 3, text: 'Sentence 3'},
{id: 4, text: 'Sentenc4 '},
];
Run Code Online (Sandbox Code Playgroud)
或者没有定义自定义类型的短语法:
const arr: Array<{id: number, text: string}> = [...];
Run Code Online (Sandbox Code Playgroud)
mic*_*yks 20
public mySentences:Array<Object> = [
{id: 1, text: 'Sentence 1'},
{id: 2, text: 'Sentence 2'},
{id: 3, text: 'Sentence 3'},
{id: 4, text: 'Sentenc4 '},
];
Run Code Online (Sandbox Code Playgroud)
更确切地说...
export interface type{
id:number;
text:string;
}
public mySentences:type[] = [
{id: 1, text: 'Sentence 1'},
{id: 2, text: 'Sentence 2'},
{id: 3, text: 'Sentence 3'},
{id: 4, text: 'Sentenc4 '},
];
Run Code Online (Sandbox Code Playgroud)
Ezi*_*zio 10
如果要存储来自外部API或数据库的数据,另一种特别有用的方法是:
创建一个表示数据模型的类
export class Data{
private id:number;
private text: string;
constructor(id,text) {
this.id = id;
this.text = text;
}
Run Code Online (Sandbox Code Playgroud)在组件类中,您创建一个类型为空的数组,Data并在从API或您正在使用的任何数据源获得响应时填充此数组
export class AppComponent {
private search_key: string;
private dataList: Data[] = [];
getWikiData() {
this.httpService.getDataFromAPI()
.subscribe(data => {
this.parseData(data);
});
}
parseData(jsonData: string) {
//considering you get your data in json arrays
for (let i = 0; i < jsonData[1].length; i++) {
const data = new WikiData(jsonData[1][i], jsonData[2][i]);
this.wikiData.push(data);
}
}
}
Run Code Online (Sandbox Code Playgroud)首先,生成一个接口
假设您使用的是TypeScript和Angular CLI,您可以使用以下命令生成一个
ng g interface car
之后设置其属性的数据类型
// car.interface.ts
export interface car {
id: number;
eco: boolean;
wheels: number;
name: string;
}
Run Code Online (Sandbox Code Playgroud)
您现在可以在所需的类中导入您的界面。
import {car} from "app/interfaces/car.interface";
并通过推送数组中的项目来更新汽车对象的集合/数组。
this.car.push({
id: 12345,
eco: true,
wheels: 4,
name: 'Tesla Model S',
});
Run Code Online (Sandbox Code Playgroud)
更多关于接口:
接口是 TypeScript 工件,它不是 ECMAScript 的一部分。接口是一种根据参数及其类型在函数上定义契约的方法。除了函数之外,接口还可以与类一起使用来定义自定义类型。接口是一种抽象类型,它不像类那样包含任何代码。它仅定义 API 的“签名”或形状。在转译过程中,接口不会生成任何代码,它仅被 Typescript 用于开发过程中的类型检查。- https://angular-2-training-book.rangle.io/handout/features/interfaces.html