我不能调用对象的数组,在我的界面,我离开我的角界面,然后我必须把它调用了打字稿的补充,但我不明白如何调用数组,如果它没有名字,如果我可以把它的名字,请给我解释一下!
Vehiculo-interface.ts
export interface vehiculointerface {
placa?: string,
[index:number]: { Ubicacion ?: string, Nombre ?: string }
id?: string
}
详细placa.component.ts
import { Component, OnInit } from '@angular/core';
import { PostService } from 'src/app/post.service';
import { ActivatedRoute,Params } from '@angular/router';
import { vehiculointerface } from '../Models/Vehiculo-interface';
@Component({
selector: 'app-detalles-placa',
templateUrl: './detalles-placa.component.html',
styleUrls: ['./detalles-placa.component.css']
})
export class DetallesPlacaComponent implements OnInit {
constructor(private post: PostService, route: ActivatedRoute) { }
private vehiculo: vehiculointerface = {
placa: "",
{ Ubicacion: "", Nombre: ""},
index() = { Ubicacion: "", Nombre: "" }
}
ngOnInit() { }
}
我不敢说我的接口中声明的对象数组[index:number]: {Ubicacion ?: string, Nombre ?: string}
我不能把我的接口中声明的对象数组Vehiculo-interface.ts
这是一个我需要detalles-placa.component.ts
此语法:
[index:number]: { Ubicacion ?: string, Nombre ?: string }
是一个指数的签名定义可索引类型。并编入索引类型是一种类型,我们可以“索引”。
你可以阅读更多关于他们在这里:https://www.typescriptlang.org/docs/handbook/interfaces.html
这里是从文档的例子:
interface StringArray {
[index: number]: string;
}
let myArray: StringArray;
myArray = ["Bob", "Fred"];
let myStr: string = myArray[0];
因此,这不是定义特定命名的属性,而是提供了一个方法来“索引”你的类型。
单独使用索引
有了您的结构,这为我工作:
private vehiculo: vehiculointerface = [{
Ubicacion: "some string",
Nombre: "some id"
},
{
Ubicacion: "other string",
Nombre: "other id"
}]
我把它当作对象的数组。 (不知道为什么你不得不因为这是注定不会被处理为阵列信息的索引属性?)
然后,您可以访问它在模板如下:
<div *ngFor="let item of vehiculo">
{{ item.Ubicacion}}; {{ item.Nombre}}
</div>
使用与其他成员的索引
我真的没有与其他成员的索引工作,所以我不能完全确定你想要达到的目的。但是,这样的事情也为我工作:
private vehiculo: vehiculointerface = {
placa: "some string",
id: "some id"
}
ngOnInit() {
this.vehiculo["some index"] = {
Ubicacion: "some string",
Nombre: "some id"
}
this.vehiculo["other index"] = {
Ubicacion: "other string",
Nombre: "other id"
}
console.log(JSON.stringify(this.vehiculo));
}
请注意如何非索引成员的定义独立索引的。
上述代码定义的接口的基本属性,然后使用分度器来设置额外的值。
最终的结构是这样的:
{
"placa":"some string",
"id":"some id",
"some index":{"Ubicacion":"some string","Nombre":"some id"},
"other index":{"Ubicacion":"other string","Nombre":"other id"}
}
然后我访问它在使用此代码模板:
<div *ngFor="let item of vehiculo2 | keyvalue">
{{ item.key}}; {{ item.value}}
</div>
但请注意,因为他们是类型[object, Object]
为索引的属性值显示为{ Ubicacion ?: string, Nombre ?: string }
这里是一个stackblitz:https://stackblitz.com/edit/angular-indexer-deborahk