误差在角度2中意味着什么?

时间:2017-12-05 06:40:07

标签: angular typescript

export class DashboardComponent implements OnInit {     
@ViewChild('modal') modal: ModalComponent;
        dashboards: IDashboard[];
        dashboard: IDashboard;    
    constructor(private fb: FormBuilder, private _dshboardService: DashboardService, private router: Router) {
                var sesssion = sessionStorage.getItem('EmpDetail');
                var ses = JSON.parse(sesssion);
                var EmpNo = ses[0].EmpNumber;
                var CompanyCode = ses[0].CompanyCode;
                this.dashboard = {};
                this.dashboard.EmpName = ses[0].EmpName;
                this.dashboard.EmpNumber = ses[0].EmpNumber;
            }
}

这会在this.dashboard = {};

行显示以下错误
  

错误TS2322类型“{}”不能分配给“IDashboard”类型   “{}”类型中缺少“EmpName”属性。

我需要将值分配给仪表板模型的属性,并在html组件

中绑定它

以下是我的IDboardboard:

export interface IDashboard {
    EmpName: string,
    EmpNumber: string,
    EmailId: string,
    FirstName: string,
    LastName: string,
    Gender: string,
    Program:string
}

2 个答案:

答案 0 :(得分:2)

错误:

this.dashboard = {};

this.dashboard有类型IDashboard,我猜它至少有一个可选字段。因此,您无需设置此必填字段即可设置对象。 类似的东西:

interface Person {
  name: string;
}

const person = {} // Error
const person1 = {name: 'Test'} // No Error


interface Person1 {
 name?: string; //name is optional field
}
 const person = {} // No Error

答案 1 :(得分:1)

你需要在构造函数或ngOninit中用空对象声明和初始化它。

您需要在组件中声明Dashboard,

const dashboard: Dashboard= {  param1: "", param2: ""...etc};