声纳发出"预期的赋值或函数调用"消息



我在NgRx工作,收到这个错误:

'预期了一个赋值或函数调用,却看到了一个表达式。'

this.sfForm.get('code')?.[this._mode ? 'disable' : 'enable']();中的声纳问题。

我不明白声纳发出的信息,也不明白该怎么解决。我需要一些帮助来理解代码并解决问题。

<mat-form-field [formGroup]="sfForm">
<input Input
matInput
(keydown.enter)="search($event.target.value)"
[type]="''"
formControlName="code"
required>
</mat-form-field>
sfForm: FormGroup;
private _mode: boolean = true;

public set scanMode(value: boolean) {
this._mode = value;
this.sfForm.get('code')?.[this._mode ? 'disable' : 'enable']();
}

以下是该行的细分:

this.sfForm.get('code') // get by the key "code"
?.                      // if `undefined` or `null`, stop here (see #1 below)
[                       // else, get prop by expression in [square brackets]
this._mode ?        // if this._mode is truthy...
'disable'       // that prop is 'disable'
: 'enable'      // else, that prop is 'enable'
]                       // (see #2 below)
()                      // call the function identified by that prop (with 0 args)
  • #1:?.的解释
  • #2:condition ? val1 : val2说明

在更详细的代码中,它可能看起来像这样:

const code = this.sfForm.get('code')
if (code !== null && typeof code !== 'undefined') {
let modeFunction
if (this._mode) {
modeFunction = code.disable
} else {
modeFunction = code.enable
}
modeFunction()
}

如果你想分配标签,你不能用这种方式。当你做

object[field]

就像您所做的那样,您不能分配值。

你能做的是这样的事情:

this.sfForm.get('code')?.[this._mode] = this.sfForm.get('code')?.[this._mode] ? 'disable' : 'enable'

或者,如果您想将字段放入变量中,则可以使用较短的方式。

另外,请注意,不能调用"?"内部的函数赋值,但仅使用语句。

最新更新