Angular MatDialog注入对象属性无法访问问题排查
问题解答
场景说明
从journeys-list组件向mat-dialog注入数据时,journey对象已成功传递到dialog组件,但访问其属性时显示undefined,不过对象本身包含所有预期值。
相关代码
journeys-list.component.ts
import { Component, OnInit } from '@angular/core'; import { MatDialog, MatDialogConfig } from '@angular/material/dialog'; import { Router } from '@angular/router'; import { DialogComponent } from '../dialog/dialog.component'; @Component({ selector: 'app-journeys-list', templateUrl: './journeys-list.component.html', styleUrls: ['./journeys-list.component.scss'] }) export class JourneysListComponent implements OnInit { constructor(private router: Router, private dialog: MatDialog) { } journeysObject: any; ngOnInit(): void { this.journeysObject = history.state; console.log(this.journeysObject); } parseTime(timestamp: any): any { const date = new Date(timestamp); return date.getHours() + ':' + date.getMinutes(); } openDialog(journey: any) { const dialogConfig = new MatDialogConfig(); dialogConfig.disableClose = true; dialogConfig.width= '50%'; dialogConfig.height= '50%'; dialogConfig.data ={journey}; this.dialog.open(DialogComponent, dialogConfig); } }
dialog-component.ts
import { Component, Inject, OnInit } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; @Component({ selector: 'app-dialog', templateUrl: './dialog.component.html', styleUrls: ['./dialog.component.scss'] }) export class DialogComponent implements OnInit { journey:any={}; constructor( public dialogRef: MatDialogRef<DialogComponent>, @Inject(MAT_DIALOG_DATA) public data: any) { this.journey = data; const type = this.journey.type; // undefined } ngOnInit(): void { } parseTime(timestamp: any): any { const date = new Date(timestamp); return date.getHours() + ':' + date.getMinutes(); } close() { this.dialogRef.close(); } }
疑问解答
对象是否已正确注入到dialog组件中?
是,对象已经正确注入,但传递数据时多包装了一层。在journeys-list.component.ts的openDialog方法里,你写的dialogConfig.data = {journey}会把目标对象放到一个新对象的journey属性中。所以dialog组件里的data结构是{ journey: 实际业务对象 },你直接把data赋值给this.journey后,this.journey.type自然不存在,真正的属性应该是this.journey.journey.type。未为对象定义合适的TypeScript类型是否是导致该问题的原因?
不是直接原因,但定义类型能提前规避这类错误。如果定义了Journey接口,传递数据时若误包装一层,TypeScript会在编译阶段就提示类型不匹配,不用等到运行时才发现属性为undefined。
修复方案
有两种可行方式:
- 方式一:修改传递逻辑,直接传入
journey对象,去掉外层包装:
// journeys-list.component.ts 的 openDialog 方法中 dialogConfig.data = journey; // 移除外层{}
此时在dialog组件中,this.journey = data后就能直接访问this.journey.type。
- 方式二:保留当前传递结构,修改dialog组件的赋值逻辑:
// dialog-component.ts 的构造函数中 this.journey = data.journey; // 取出内层的业务对象 const type = this.journey.type; // 此时可正确获取属性值
内容的提问来源于stack exchange,提问作者Ayub Jamal
相关产品推荐
相关产品推荐

