You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Mat Dialog中评论变量未定义问题求解

你的代码里存在以下几处错误,逐一修改后即可解决val为undefined的问题:

1. 对话框组件变量声明与存储逻辑错误

你的reasonpopup组件中val写的是类型声明,没有赋初始值,实际默认值为undefined,同时存储值的时机错误:
原变量声明代码:

val : " " 

修改为:

val: string = ""

删除ngOnInit中提前存值的逻辑(此时用户还未输入内容),改为提交时再更新共享服务的存储值:

// 删掉原ngOnInit里的setMessage调用
ngOnInit(): void {}

onSubmit() { 
    this.shared.setMessage(this.val); // 提交时才存储用户输入的内容
    this.MatDialogRef.close(this.val); 
}

2. 对话框模板按钮绑定逻辑冲突

你的YES按钮同时绑定了onSubmit和[mat-dialog-close]="data.text",其中data.text不存在,会覆盖你要传递的val值,删除该属性即可:
原按钮代码:

<button
    mat-raised-button
    [disabled]="userForm.invalid"
    id="yes-button"
    (click)="onSubmit()" 
    (click)="getValue(text.value)"
    [mat-dialog-close]="data.text" 
    cdkFocusInitial
>

修改后:

<button
    mat-raised-button
    [disabled]="userForm.invalid"
    id="yes-button"
    (click)="onSubmit()"
    cdkFocusInitial
>

3. 调用post的组件取值逻辑错误

你在saveRow方法中直接使用this.val,但该组件没有声明和赋值val变量,需要从共享服务ReasonpopupService中取值:
首先在该组件的构造函数中注入ReasonpopupService:

constructor(
    // 保留原有其他注入逻辑
    private reasonService: ReasonpopupService
) {}

然后修改saveRow方法,把评论内容加到请求体中:

saveRow() {
    let addRowsRequest = {
        IstValues: this.dataSource.data.filter(r => r.editing),
        comment: this.reasonService.getMessage() // 从共享服务取评论内容
    };
    this.istManagementService.postRecord(this.inputTable, addRowsRequest).subscribe(
        (res: any) => {
            const editData = this.dataSource.data.filter(r => r.editing);
            this.dataSource.data.push(...editData); // 解构数组再push,避免把整个数组当单个元素插入
            this.dataSource._updateChangeSubscription();
        }
    )
}

4. 修正post接口调用逻辑

原来的postRecord第三个参数传message是错误的,Angular HttpClient.post的第三个参数是请求配置项,不是请求体参数,直接把评论加到addRowsRequest请求体中即可:
修改IstManagementService中的postRecord方法:

postRecord(inputTable: string, addRecord: any) {
    return this.httpClient.post(environment.apiRoot + "/StaticTable/Add/" + inputTable, addRecord);
}

如果还要用到该服务内的message相关方法,修正getMessage的逻辑错误:
原代码:

getMessage(){
    return this.getMessage
}

修改为:

getMessage(){
    return this.message
}

内容的提问来源于stack exchange,提问作者leandroter7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 20:18:05