错误:输入'{firstName:string; lastName:string;年龄:数量; ...'不能用作索引类型

时间:2018-05-31 07:38:09

标签: angular angular5 angular6

我正在尝试将用户列表添加到数组中,它会抛出上面提到的错误

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"
      }
    }
   ];

  }

}

任何人都可以解释我在哪里犯了错误。 Program Error

1 个答案:

答案 0 :(得分:0)

代码应该是 -

ngOnInit() {
   this.users = [
    {
      firstName: "John",
      lastName: "Doe",
      age: 30,
      address : {
        street: "3rd Cross",
        city: "Bangalore",
        state: "Karnataka"
      }
    }
   ];

  }

如错误解释,您没有将值设置为变量。相反,您正在尝试将值添加为格式错误的数组的索引。