如何将 属性 分配给 Typescript 中的 Class 成员

How to Assign a Property to the Class members in Typescript

我是一个 Java 人,正在学习 Type Script 但是我遇到了这种情况...!!

我有一个Class喜欢

export class Human{

    public name: string;
    public surname: string;
    public status:ApprovalStatus(Its an Enum);
  
    constructor( human: Human) {
      Object.assign(this, human);
    }

我有一个 Angular Material 的对话,我在其中传递了这个 Object Human 并填充了值,例如 name='ABC' 和 surname='PQR'and status=ApprovalStatus.NOT_APPROVED

Angular material 对话是一个单独的组件,构造函数就像

openDialog() {
    const dialogRef = this.dialog.open(DialogComponent,{
    data:{human:this.human},
    disableClose: true });

    dialogRef.afterClosed().subscribe(result => {
      console.log(result)
    });
  }

这就是调用对话和接收数据的方式..!!

constructor(@Inject(MAT_DIALOG_DATA) public human: any,private dialogRef: MatDialogRef<DialogComponent>) {}

所以我将在 human 中接收数据,现在我想通过修改对象来发回数据,人类喜欢设置与 [ 不同的状态=41=] 到 ApprovalStatus.APPROVED

所以基本上我正在做的是

public confirm() {
    let humanData=<Human>this.human;
    human.status=ApprovalStatus.APPROVED;
    this.dialogRef.close({ data: humanData}) // send data to parent component
  }

所以在另一个组件上,我分别收到两件事,一个是 status,另一个是 human Object,它没有被修改为已批准状态甚至在 confirm() 方法中都没有有人指出如何处理这个?

是否有理由在您的构造函数中键入 human: any 然后断言它在您的组件中是 <Human>

我会更新您的构造函数以正确输入它

constructor(@Inject(MAT_DIALOG_DATA) public human: Human,private dialogRef: MatDialogRef<DialogComponent>) {}

我认为您的代码也会出错,因为您正在为 human.status 分配一个不应定义的值。

public confirm() {
    // this line was not needed, you already have this.human and its not going point to the same object in memory anyway
    //let humanData=<Human>this.human;

    // human is not even defined, so this wont work
    //human.status=ApprovalStatus.APPROVED;

    // we will set the property on the real object this time
    this.human.status = ApprovalStatus.APPROVED;

    // this should have the right data
    console.log('human inside the dialog', this.human);

    // return this.human
    this.dialogRef.close({ data: this.human}) // send data to parent component
  }

human对象传递给对话框时出错,应该是:

openDialog() {
    const dialogRef = this.dialog.open(DialogComponent,{
        data: this.human,
        disableClose: true
    });

    dialogRef.afterClosed().subscribe(result => {
        console.log(result)
    });
}

所以 data: {human: this.human} 应该是 data: this.human.

在您的对话框中,数据是 {human: this.human}。 所以

this.human.status = `xxx`

将使数据为:

{human: this.human, status: 'xxx'}