ngModel值在add函数中未定义



我有一个添加/编辑规则的窗口。

我有一个组件";规则编辑"编辑或创建规则。编辑部分工作正常,但当我尝试添加规则时,选择器中出现错误:ERROR TypeError: _co.rule.selectors is undefined

RuleEditComponent.html:

<div fxLayout="row" fxLayoutGap="10px">
<div class="sub-labels" fxFlex="50%;">
<label i18n>IP</label>
</div>
<div fxFlex="50%;">
<input id="ruleedit-ipsource" type="text" autofocus [(ngModel)]="selectors.ip" <--- error here
[disabled]="!permEditConfig" formControlName="ip">
</div>
</div>

添加/编辑功能:

addRule() {
const dialogRef = this.dialog.open(RuleEditComponent, {
data: { rule: new Rule() },
width: '600px',
disableClose: false,
});
dialogRef.afterClosed().subscribe((result) => {
if (result) {
this.reloadRules();
}
});
}
editRule(rule: Rule & { actionsLocked: boolean }) {
rule.actionsLocked = true;
this.actionsLocked = true;
this.configService.rule(rule.id, rule.type).then((rule: Rule) => {
const dialogRef = this.dialog.open(RuleEditComponent, {
data: { rule },
width: '600px',
disableClose: false,
});
dialogRef.afterClosed().subscribe((result) => {
if (result) {
this.reloadRules();
}
});
}).catch(() => {
this.notifier.notify('error', 'Couldn't get rule details');
}).finally(() => {
this.actionsLocked = false;
rule.actionsLocked = false;
});
}

服务器端选择器是python中的一个dict,它可以是空的。

我被卡住了,因为我不知道如何解决这个未定义的错误。

这可能是因为规则对象的选择器(以及其中的ipSource(属性尚未初始化。

因此,在对该对象执行任何操作之前,您需要使用默认值对其进行初始化(或者,在编辑时对其进行修补(。

const rule = new Rule();
rule.selectors = new Selectors();
rule.selectors.ipSource = ''; // or, something

现在,将其传递给dialog.open(),如下所示:

data: { rule },

此外,添加如下可选链接:

[(ngModel)]="rule?.selectors?.ipSource"

当你说这样的时

data: { rule: new Rule() }

您生成了Rule类型的对象。这是事实。但它只是一个空船体。未设置所有属性,但设置了undefined。如果需要,您必须至少用伪值填充它们。

这就是您出现错误的原因。

如果你想避开它,你可以使用Elvis Operator?.

<div fxFlex="50%;">
<input id="ruleedit-ipsource" type="text" autofocus 
[(ngModel)]="rule?.selectors?.ipSource"
[disabled]="!permEditConfig" formControlName="ipSource">
</div>

最新更新