如何将动态属性/参数传递给openDialog?
问题描述:
我需要将以下ID:59dc921ffedff606449abef5
动态地传递给MatDialog
。对于测试建议我使用它作为硬编码的ID。如何将动态属性/参数传递给openDialog?
不幸的是,我所有的搜索和尝试都失败了,我无法动态地将该ID获取到函数调用中。我也尝试了@input
功能,但它没有帮助。
edit-dilog.component.ts
:
export class EditDialogComponent implements OnInit {
dialogResult:string = '';
constructor(public dialog:MatDialog, public loginService:LoginService){ }
ngOnInit() {}
openDialog() {
this.dialog.open(EditUserComponent, { data: '59dc921ffedff606449abef5' })
.afterClosed()
.subscribe(result => this.dialogResult = result);
}
}
edit-user.component.ts
:
export class EditUserComponent implements OnInit {
public message:any [];
public resData: {};
constructor(public thisDialogRef: MatDialogRef<EditUserComponent>,
@Inject(MAT_DIALOG_DATA) public data: number,
public loginService: LoginService) { }
ngOnInit() {
this.loginService.getSingleUser(this.data)
.subscribe(data => {
this.resData = JSON.stringify(data);
})
}
onCloseConfirm() {
this.thisDialogRef.close('Confirm');
}
onCloseCancel() {
this.thisDialogRef.close('Cancel');
}
}
将ID从在服务JSON响应来登录-service.ts:
getSingleUser(id) {
return this.http.get(environment.urlSingleUsers + '/' + id, this.options)
.map(res => {
console.log('RES: ' + JSON.stringify(res.json()));
return res.json();
}).catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
extractData(result:Response):DialogUserData[] {
return result.json().message.map(issue => {
return {
ID: issue._id,
Email: issue.email,
Name: issue.fullName
}
});
}
这里是我做的openDialog()
电话:
<i class="material-icons" (click)="openDialog()">create</i>
更多的澄清这里是JSON响应如何产生:
"message": [
{
"_id": "59415f148911240fc812d393",
"email": "[email protected]",
"fullName": "Jane Doe",
"__v": 0,
"created": "2017-06-14T16:06:44.457Z"
},
{
"_id": "5943b80be8b8b605686a67fb",
"email": "[email protected]",
"fullName": "John Doe",
"__v": 0,
"created": "2017-06-16T10:50:51.180Z"
}
]
答
我只是做了类似的事情,但我对你如何命名组件感到困惑(似乎应该是相反的方式)。
您可以尝试:在你的控制组件获取数据(用户)先升后(实际上)打开对话框:
编辑dialog.component.ts:
openDialog(id: string) {
this.loginService.getSingleUser(id)
.subscribe(user=> {
const dialogRef = this.dialog.open(EditUserComponent, {
data: user
});
dialogRef.afterClosed().subscribe(result => {
console.log(`Dialog result: ${result}`);
});
});
}
你然后可以访问对话数据(用户)呈现的对话框视图:
编辑user.component.ts:
ngOnInit() {
console.log(this.data);
}
通过这种方式,可以动态传递ID:
<i class="material-icons" (click)="openDialog(id)">create</i>
其中id
可以是你的控制组件中的一员。