angular - 错误:键入'{ firstName:字符串;姓氏:字符串;年龄:数字;...' 不能用作索引类型
问题描述
我正在尝试将用户列表添加到数组中,它会抛出上述错误
export interface User{
firstName:string;
lastName:string;
age:number;
address:{
street:string,
city:string,
state:string
}
}
这是我的界面
在这里我试图添加类型为 user[] 的用户
import { Component, OnInit } from '@angular/core';
import { User } from '../../models/User';
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
//Properties
users :User[];
//Methods
constructor() { }
ngOnInit() {
this.users[
{
firstName: "John",
lastName: "Doe",
age: 30,
address : {
street: "3rd Cross",
city: "Bangalore",
state: "Karnataka"
}
}
];
}
}
谁能解释一下我在哪里犯了错误。 程序错误
解决方案
代码应该是 -
ngOnInit() {
this.users = [
{
firstName: "John",
lastName: "Doe",
age: 30,
address : {
street: "3rd Cross",
city: "Bangalore",
state: "Karnataka"
}
}
];
}
如错误中所述,您没有将值设置为变量。相反,您试图将值添加为格式错误的数组的索引。
推荐阅读
- css - 如何添加图像阴影
- javascript - 我收到错误:运行我的反应项目时无法读取未定义的属性“then”
- python - 如何在 Django 中访问 ForeignKey 的其他属性?
- ios - 上传 ionic ios 应用程序时出错。应用程序中使用的已弃用 UIWebView
- android - Android 错误:尝试在空对象引用上调用虚拟方法“void androidx.appcompat.app.ActionBar.hide()”
- java - 如何在 Google Kubernetes Engine 集群中启用客户端证书
- html - 如何让社交媒体句柄位于图标的右侧?
- java - 我想隐藏一个回收器视图,另一个是滚动的
- c# - 基于datagridview WPF动态添加标签和文本框
- javascript - 如何有条件地导入 react-devtools?