簡體   English   中英

使用 combineLatest 和 Rxjs 返回 observable 的結果

[英]Return result of an observable with combineLatest and Rxjs

我希望得到一個 observable 的結果,每次值改變時都會減去默認值

每次值更改時,它都會用輸入字段中輸入的新值減去默認值

例如默認值為 5。

我在輸入字段中輸入 4

結果是 5-4 = 1 所以我希望在輸入字段“Surface ha”中顯示 1

我清除該字段然后輸入 3 結果是 5-3 = 2 所以我希望在輸入字段“Surface ha”中顯示 2

就這樣……

如果我執行 console.log,我可以清楚地看到 observable 的結果,但是,我希望將 observable 的結果顯示到同一個輸入字段中

我只在我的開發控制台中得到這種錯誤結果:

NaN

風景:

   <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;

您需要將 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'>

我忘了從不同的默認值開始!

            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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM