Angular 8 : 如何对可观察对象的两个属性进行计算并需要保存在另一个 属性
Angular 8 : How to do calculation on observable object's two properties and need to save on another property
我需要显示可观察数据的两个属性之和。这是我的代码请告诉我如何修复它。
打字稿class
export class Amount {
Amount1: number;
Amount2: number;
Total:number;
}
在打字稿服务中:
我已经声明了可观察对象
export class AmountService {
public newmessageService = new BehaviorSubject(new Amount());
public Model = this.newmessageService.asObservable();
}
在组件 Class 中:
在计算组件中订阅了那个可观察模型
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 的总和。
谢谢。
可以考虑把Total
属性转成getter.
export class Amount {
Amount1: number;
Amount2: number;
get Total():number {
return this.Amount1 + this.Amount2;
};
}
请尝试
ngDoCheck( ){
this.service.Model.subscribe(temp => {
this.Model$ = temp;
this.Model$.Total = Number(this.Model$.Amount1) + Number(this.Model$.Amount2);
});
}
我需要显示可观察数据的两个属性之和。这是我的代码请告诉我如何修复它。
打字稿class
export class Amount {
Amount1: number;
Amount2: number;
Total:number;
}
在打字稿服务中:
我已经声明了可观察对象
export class AmountService {
public newmessageService = new BehaviorSubject(new Amount());
public Model = this.newmessageService.asObservable();
}
在组件 Class 中:
在计算组件中订阅了那个可观察模型
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 的总和。
谢谢。
可以考虑把Total
属性转成getter.
export class Amount {
Amount1: number;
Amount2: number;
get Total():number {
return this.Amount1 + this.Amount2;
};
}
请尝试
ngDoCheck( ){
this.service.Model.subscribe(temp => {
this.Model$ = temp;
this.Model$.Total = Number(this.Model$.Amount1) + Number(this.Model$.Amount2);
});
}