我需要显示可观察数据的两个属性之和。这是我的代码,请给我建议如何解决。
Typescript类
export class Amount {
Amount1: number;
Amount2: number;
Total:number;
}
在打字稿服务中:
我已经声明了可观察对象
export class AmountService {
public newmessageService = new BehaviorSubject(new Amount());
public Model = this.newmessageService.asObservable();
}
在组件类别:
计算组件中订阅了该可观察模型
export class Calculation implements OnInit {
Model$:Amount;
ngOnInit() {
this.service.Model.subscribe(temp => this.Model$ = temp)
}
}
在组件视图中:
在视图中,为输入声明Amount1和Amount2属性,并显示合计。
<form name="calculationform">
<mat-form-field class="example-full-width">
<mat-label>Amount1</mat-label>
<input matInput [(ngModel)]="Model$.Amount1" name="Amount1">
</mat-form-field>
<mat-form-field class="example-full-width">
<mat-label>Amount2</mat-label>
<input matInput [(ngModel)]="Model$.Amount2" name="Amount2">
</mat-form-field>
<mat-label>Total:</mat-label>
<mat-label>{{Model$.Total}}</mat-label>
</form>
当我们更改金额时,我需要在Total属性上显示Amount1和Amount2之和。
谢谢。
this.service.Model.subscribe(temp => {
this.Model$ = temp;
this.Model$.map(model => ({...model, Total: (Number(model.Amount1) + Number(model.Amount2)})));
});
您可以考虑将Total
属性转换为吸气剂。
export class Amount {
Amount1: number;
Amount2: number;
get Total():number {
return this.Amount1 + this.Amount2;
};
}