angular - 使用 combineLatest 和 Rxjs 返回 observable 的結果
我希望獲取一個可觀察對象的結果,每次值變化時都減去默認值
每次數值改變時,它會用輸入欄中輸入的新數值減去預設值
例如,預設值是 5。
我在輸入欄位中輸入4
結果是 5-4=1,所以我希望將 1 顯示在輸入欄位“Surface ha”中
我清空欄位,然後輸入 3,結果是 5-3=2,所以我希望將 2 顯示在輸入欄位「Surface ha」中
然後然後....
如果我使用 console.log,我可以清楚地看到 observable 的結果,但我希望將 observable 的結果顯示在同一個輸入欄位中
我在開發控制台中只得到這種錯誤結果:
非數值
景色:
<form [formGroup]="credentialsForm" *ngIf="credentialsForm">
<mat-form-field class="example-full-width">
<mat-label>Surface Ha</mat-label>
<input matInput type="number" [value]="surface" placeholder="Libellé" formControlName='surface'>
</mat-form-field>
<ion-input class="form-control" placeholder="Valeur"
formControlName="0">
</ion-input>
</form>
在元件內:
this.surface = 5;
const observedValues = ['0']
.map(key => this.credentialsForm.controls[key].valueChanges.map(value => +value).startWith(0))
const resSurface = combineLatest(observedValues)
.pipe(map(([value0]) => { return this.surface - value0 }));
const res = resSurface.subscribe(val => { return val });
// These line below should display the "res" value
this.surface = res;
答案#1
你需要將 Observable 發出的值指派給 this.surface,而不是指派訂閱本身:
resSurface.subscribe(val => this.surface = val);
或者,你可以去掉 subscribe 調用,使用 Angular 的 async 管道直接綁定到 Observable:
this.resSurface = combineLatest(observedValues)
.pipe(map(([value0, value1, value2]) => { return this.surface - (value0 + value1 + value2) }));
然後在你的範本中:
<input matInput type="number" [value]="resSurface | async" placeholder="Libellé" formControlName='surface'>
答案#2
我忘了從不同的預設值開始!
let defaultValueSurface = 5;
const observedValues = ['0']
.map(key => this.credentialsForm.controls[key].valueChanges.map(value => +value).startWith(0))
const resSurface = combineLatest(observedValues)
.pipe(map(([value0]) => { return defaultValueSurface - value0 }));
const res = resSurface.subscribe(val => { return val });
this.surface = res;
