垫对话框传递数组

Mat Dialog pass array

当用户单击按钮以显示信息时,它会打开垫对话框。但是弹出框是空白的,数据没有通过。

<form [formGroup]="userForm">
        <input type="text" formControlName="name" placeholder="Name" />
        <button class="ghost" (click)=onSubmit()>Click</button>
</form>

export class LoginComponent implements OnInit {

    data: User[] = [];
    
    constructor(private dialog: MatDialog) { }
    
    onSubmit() {
    this.registerService.getUser(this.name).subscribe((response: Array<User>) => {
      this.data = response;
    });
    
    return this.dialog.open(PopupRegisterComponent, {
      disableClose: true,
      autoFocus:true,
      data: this.data,
    });
}

export class PopupRegisterComponent implements OnInit {

  constructor(@Inject(MAT_DIALOG_DATA) public data: User) { }

  ngOnInit() {
    console.log( this.data.name );
    console.log( this.data);
  }
}

Subscribe 是异步的,因此您需要在其中打开对话框:

onSubmit() {
  this.registerService.getUser(this.name).subscribe((response: Array<User>) => {
    this.data = response;
    
    // this.data isn't required here of course, depending on if you use these data elsewhere
    this.dialog.open(PopupRegisterComponent, {
      disableClose: true,
      autoFocus:true,
      data: this.data,
    });
});

您也不需要 return 某些东西。除非你正在处理对话框引用,但我不这么认为。