[英]In Angular 8, how to pass dynamic data from an observable to a modal-dialog?
在 Angular 8 我想实现一个 Angular-Material Modal-Dialog。 单击用户图像后,用户数据应显示在模态中。 我无法将可观察对象的动态数据从 Profile 组件传递到 Profile-Modal 组件。 为了进行测试,我订阅了 Profile.component.ts 的 ngOnInit() 中的可观察对象,数据对象数组已正确记录到控制台。 如果我在用于打开模态对话框的 openDialog() 中使用相同的订阅,我会收到此错误消息:找不到不同的支持 object 类型为“对象”的“[对象对象]”。 NgFor 仅支持绑定到 Iterables,例如 Arrays。在 NgForOf.ngDoCheck
profile.component.ts :(在 profile.component.html 中一切正常,*ngFor="let member of members" 正常工作并且通过插值我得到了数据,即 {{member.name }})
import { Component, OnInit } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { MatDialog } from '@angular/material';
import { ProfileModalComponent } from '../profile-modal/profile-modal.component';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
observableData: observableData[] = [];
members: Observable<any[]>;
constructor(db: AngularFirestore,
public dialog: MatDialog) {
this.members = db.collection('members').valueChanges();
}
openDialog(): void {
let observableData = this.members.subscribe(members => members);
this.dialog.open(ProfileModalComponent, {
width: '80%',
height: '80%',
data: {data: observableData}
});
}
// logs the array with the objects
ngOnInit() {
const members = this.members.subscribe(
member => console.log(member)
)
}
}
配置文件-modal.component.ts:
import { Component, Inject, Input } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
@Component({
selector: 'app-profile-modal',
templateUrl: 'profile-modal.component.html',
styleUrls: ['profile-modal.component.css']
})
export class ProfileModalComponent {
constructor(public dialogRef: MatDialogRef<ProfileModalComponent>,
@Inject(MAT_DIALOG_DATA) public data: any) {}
onNoClick(): void {
this.dialogRef.close();
}
}
我认为您可以在收到如下数据后打开模态:
openDialog(): void {
this.members.subscribe(members => {
this.dialog.open(ProfileModalComponent, {
width: '80%',
height: '80%',
data: {data: members }
});
});
}
试试这个它可以解决问题。
如果 ngFor 允许使用异步 pipe,请使用它。 也许这种方式有效:
ngFor="let member of data | async"
更新
在查看了您的 stackblitz 之后,我在这里为您的问题创建了一个修复程序https://stackblitz.com/edit/angular-vwhas1
问题出在您的 *ngFor 中。 它应该是let member of data.data
。
因为你已经像这样分配了 observable:
data: {data: observableData}
,这意味着在你的 modal/dialog 组件中,你可以通过data.data
访问它
您的固定代码
<fa-icon id="closeModal" class="icon" [icon]="faTimes" (click)="onNoClick()">
</fa-icon>
<div class="container">
<h1 mat-dialog-title>Profil</h1>
<div mat-dialog-content>
<div class="member" *ngFor="let member of data.data">
<span>NAME: </span>
<span>{{member.name}}</span>
</div>
</div>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.