我創建了一個名稱為 registration.ts 的模型類
export class CustomerRegistration{
customer: {
firstname : string;
lastname : string;
email: string;
}
password: string;
}
然后我創建了一個組件,在該組件中,我試圖在上面的類中設定值
import { Component, OnInit } from '@angular/core';
import { CustomerRegistration} from 'src/app/classes/customer/registration';
@Component({
selector: 'app-userregistration',
templateUrl: './userregistration.component.html',
styleUrls: ['./userregistration.component.css']
})
export class UserregistrationComponent implements OnInit {
ngOnInit(): void {
}
register = new CustomerRegistration();
hello(){
this.register.customer.firstname= 'Karan';
console.log(this.register);
}
}
但是當我嘗試在名字中設定值時,我收到以下錯誤
core.js:6456 錯誤型別錯誤:無法設定未定義的屬性(設定“名字”)
誰能幫我設定名字的值。
uj5u.com熱心網友回復:
您的customer屬性基本上是一個陣列,因此您無法使用點 (.) 運算子訪問內部屬性。
您必須使用陣列索引訪問它,如下所示:
this.register.customer[0].firstname= 'Karan';
這里 0 是一個索引,它將動態更改基于索引值。
uj5u.com熱心網友回復:
你的customer屬性應該被實體化。您可以在類建構式中執行此操作:
export class CustomerRegistration {
constructor(){
this.customer = {} as any;
}
customer: {
firstname: string;
lastname: string;
email: string;
};
password: string;
}
另外,請考慮使用如下介面:
export interface ICustomer{
firstname : string;
lastname : string;
email: string;
}
export interface ICustomerRegistration{
customer: ICustomer;
password: string;
}
然后在您的組件中:
Register:ICustomerRegistration = {customer:{} as ICustomer} as ICustomerRegistration;
Register.customer.firstname = 'Karan';
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/325404.html
上一篇:重復一行代碼而不需要再寫一遍
