【问题标题】:cannot assign to 'total' because it is a constant or a read only property for function get total(){}无法分配给“总计”,因为它是函数 get total(){} 的常量或只读属性
【发布时间】:2019-02-01 17:50:41
【问题描述】:

当我在项目中使用此命令 ng build --prod 时,显示此错误。 无法分配给“total”,因为它是函数 get total(){}

的常量或只读属性

我的功能是:

  get total() {
         return this.products
          .map(p => p.Unit_price * p.Quantity)
          .reduce((a, b) => a + b, 0);
      }

HTML:

<form [formGroup]="addsale" (ngSubmit)="onaddsale()" >
  <div class="row">
    <div class="input-field col s2" style="float: right;">
      <label for="total">Total {{total}} ALL</label>
      <input formControlName="total" id="total" type="text" class="validate" [value]="total" [(ngModel)]="total">
    </div>
    <div class="input-field col s2" style="float: right;">
      <label for="amount_paid">Amount Paid:</label>
      <input formControlName="amount_paid" id="amount_paid" [value]="total" type="text" class="validate" [(ngModel)]="total">
    </div>
    <div class="input-field col s2" style="float: right;">
      <label for="total">Subtotal</label>
      <input formControlName="Subtotal" id="Subtotal" type="text" class="validate" [value]="total" [(ngModel)]="total">
    </div>
  </div>
</form>

Ts 形式:

   this.addsale = this.fb.group({
      'amount_paid': new FormControl('', Validators.required),
       'Subtotal': new FormControl('', Validators.required),
      'total': new FormControl('', Validators.required)
    });

有什么想法吗?

【问题讨论】:

  • 这对我有用。您使用的是什么 Angular 和 cli 版本?你能运行“ng serve”吗?
  • 你试过在 total() 之前不使用 'get' 吗?
  • 如果你只是'返回5',它是否有效; (例如)?
  • @ForestG "@angular/cdk": "^5.1.1", "@angular/cli": "^1.6.2",当我运行 ng serve 时,效果很好
  • 你能说明你在哪里使用它吗?或者你在哪里使用total 变量?

标签: angular typescript


【解决方案1】:

使用 --prod 标志构建实际上是使用 aot 构建的,这比仅使用 ng serve 时严格得多。

我认为这是因为您的 [(ngModel)] 对于所有字段都设置为 total,并使用 2 路绑定(get/set);你和total getter 有冲突

由于计算了总数,我认为为total 进行双向绑定是没有意义的,它应该是只读的。并且支付的小计/金额不应使用total for ngModel

【讨论】:

  • 拜托,你能提出任何解决方案吗?我在使用[value]="total" type="text" class="validate" [(ngModel)]="total"时遇到这个问题或者请任何例子来计算总数?
【解决方案2】:

我有同样的问题,但在我的情况下是指表单的有效状态。

<-- HTML-->
<button 
    type="submit"
    [(disabled)]="!loginForm.valid">
    Enter
</button>

对我有用的是将该检查分配给一个新的公共变量。

<-- JS -->
public validForm: boolean;

 ngOnInit() {
     this.validForm = this.loginForm.valid;
 }
<-- HTML -->
<button 
    type="submit" 
    [(disabled)]="!validForm">
    Entrar
</button>

如果我们只使用一种方式数据绑定也可以工作

<button 
    type="submit" 
    [disabled]="!loginForm.valid">
    Entrar
</button>

【讨论】:

    猜你喜欢
    • 2018-10-14
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    相关资源
    最近更新 更多