javascript - Angular 的垫子对话框文本中未定义变量的问题
问题描述
我使用 Angular 创建了一个对话框,以收集信息并将其保存在我的后端。
问题是当我使用我的 post 方法将它发送到我的后端时,评论的变量保持未定义。有问题的变量是:
值:“”
这是我的对话 ts 文件:
import { Component, OnInit, Inject } from '@angular/core'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { IstManagementService } from './../../core/services/ist-management.service'; import { ReasonpopupService } from 'ClientApp/app/core/services/reasonpopup.service';
@Component({
selector: 'app-reasonpopup', templateUrl: './reasonpopup.component.html', styleUrls: ['./reasonpopup.component.css'] }) export class ReasonpopupComponent implements OnInit {
val : " "
/* reason2 : string = this.reason */
onSubmit() { this.MatDialogRef.close(this.val); }
getValue(val:string){
console.log(val)
}
constructor(
private istManagementService: IstManagementService,
public MatDialogRef: MatDialogRef<ReasonpopupComponent>,
@Inject(MAT_DIALOG_DATA) public data: any,
private shared:ReasonpopupService,
) { }
ngOnInit(): void {
this.shared.setMessage(this.val) }
reason :string closeDialog() {
this.MatDialogRef.close(false); }
}
我的html文件:
<div>
<div class="content-container">
<mat-icon id="close-icon" (click)="closeDialog()">close</mat-icon>
<span class="content-span full-width">{{ data.message }}</span>
</div>
<form #userForm="ngForm">
<div class="input-reason">
<mat-form-field class="example-full-width" appearance="fill" [style.width.px]=420 style="padding-bottom: 100px;" >
<mat-label>Leave a comment</mat-label>
<textarea
[(ngModel)]="val"
type="text"
ngModel class="form-control"
required
#text
minlength="3"
class="form-control"
name="tx"
matInput
placeholder="please describe the reason"
></textarea>
<span *ngIf="text.invalid && text.touched" class="error">input the reason</span>
</mat-form-field>
</div>
<button mat-raised-button id="no-button" [mat-dialog-close]="false">NO</button>
<button
mat-raised-button
[disabled]="userForm.invalid"
id="yes-button"
(click)="onSubmit()"
(click)="getValue(text.value)"
[mat-dialog-close]="data.text"
cdkFocusInitial
>
YES
</button>
</form>
</div>
我将变量作为参数传递给具有 post 方法的其他组件的方法
saveRow() {
let addRowsRequest = {
IstValues: this.dataSource.data.filter(r => r.editing)
};
console.log(this.val)
this.istManagementService.postRecord(this.inputTable, addRowsRequest, this.val).subscribe(
(res: any) => {
console.log(this.dataSource.data.filter(r => r.editing));
this.dataSource.data.push(this.dataSource.data.filter(r => r.editing));
this.dataSource._updateChangeSubscription();
}
)
}
我创建的用于在组件之间共享变量的 setter 和 getter 服务
mport { ReasonpopupComponent } from './../../tasks/reasonpopup/reasonpopup.component';
import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
@Injectable({
providedIn: 'root'
})
export class ReasonpopupService {
val:string
constructor(private messageDialog: MatDialog) { }
openReasonDialog(msg: string) {
return this.messageDialog.open(ReasonpopupComponent, {
width: '570px',
panelClass: 'confirm-dialog-container',
disableClose: true,
data: { message: msg }
})
}
setMessage(data: string){
this.val=data
console.log(this.val)
}
getMessage(){
return this.val
}
}
最后,我的服务包含所有 CRUD 方法
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { ISTGenericResponse } from '../../pages/ist-management/ist-generic-response';
import { environment } from 'ClientApp/environments/environment';
@Injectable({
providedIn: 'root'
})
export class IstManagementService {
constructor(private httpClient: HttpClient) { }
public getGenericStaticTablesFiltered(inputTable: string, inputKey: string, inputValue: string, inputComparison: string): Observable<ISTGenericResponse> {
var filter = "";
if (inputKey && inputValue) {
filter = "?key=" + inputKey + "&value=" + inputValue + "&comparison=" + inputComparison;
return this.httpClient.get<ISTGenericResponse>(environment.apiRoot + "/StaticTable/Filter/" + inputTable + filter);
}
else {
return this.httpClient.get<ISTGenericResponse>(environment.apiRoot + "/StaticTable/" + inputTable);
}
}
message:string
setMessage(data: string){
this.message=data
}
getMessage(){
return this.getMessage
}
postRecord(inputTable: string, addRecord: any, message:any ) {
return this.httpClient.post(environment.apiRoot + "/StaticTable/Add/" + inputTable, addRecord, message);
}
deleteRecord(inputTable: string, deleteRecord: any) {
const headers = new HttpHeaders({ 'Content-Type': 'application/json; charset=utf-8' });
return this.httpClient.request('delete', environment.apiRoot + "/StaticTable/Delete/" + inputTable, { body: deleteRecord, headers: headers });
}
editRecord(inputTable: string, editRecord: any): Observable<any> {
const headers = new HttpHeaders({ 'Content-Type': 'application/json; charset=utf-8' });
return this.httpClient.request('put', environment.apiRoot + "/StaticTable/Update/" + inputTable, { body: editRecord, headers: headers, });
}
}
谢谢先进
解决方案
根据这段代码,你在方法this.shared.setMessage(this.val)
内部调用ngOnInit()
ReasonpopupComponent
这将始终未定义,因为ngOnInit()
仅在用户输入任何数据之前在组件的初始化时调用。
你需要做的是在方法this.shared.setMessage(this.val)
内部移动onSubmit()
,所以最后它看起来像这样
export class ReasonPopupComponent implements OnInit {
val = '';
constructor(
private istManagementService: IstManagementService,
public MatDialogRef: MatDialogRef<ReasonPopupComponent>,
@Inject(MAT_DIALOG_DATA) public data: any,
private shared:ReasonpopupService,
) { }
ngOnInit(): void {
}
onSubmit() {
this.shared.setMessage(this.val);
this.MatDialogRef.close(this.val);
}
closeDialog() {
this.MatDialogRef.close(false);
}
}
更好的是,如果您的“其他组件”是打开弹出窗口的那个,您可以使用角度材料对话框订阅者。正如您在onSubmit()
方法this.matDialogRef.close(this.val)
中看到的那样,已经使用该值调用了该方法。您需要做的就是像这样在“其他组件”上订阅它。
dialogRef.afterClosed().subscribe(result => {
console.log(result)
});
推荐阅读
- android - 重新打开应用程序时打开最后显示的片段的最佳方法是什么?
- powershell - Powershell - 循环运行控制台应用程序>等待 Ctrl+c
- pattern-matching - 对象模式匹配导致未初始化的变量
- reactjs - Reactjs 中的 Material-ui 表服务器端分页
- ansible - Ansible:如何定义 localhost os_family 条件
- python - groupby 函数:df.groupby(by=["b"]).sum()
- node.js - 我在尝试运行 serve -s build 时收到错误消息
- python - Python 网络钩子 API
- r - How to link 2 widget options dynamically in R Shiny?
- javascript - 应该用间隔替换多少超时?