【问题标题】:Return result of an observable with combineLatest and Rxjs使用 combineLatest 和 Rxjs 返回 observable 的结果
【发布时间】:2021-03-06 11:44:33
【问题描述】:

我希望得到一个 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;

【问题讨论】:

    标签: angular typescript rxjs observable


    【解决方案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'>
    

    【讨论】:

    • 对不起,我没有解释清楚,我希望重用“res”值在表单视图上显示它
    • 啊,我想我明白了 - 我已经编辑了我的答案。
    • resSurface.subscribe(val => this.surface = val);重新定义 this.surface 但我希望返回 observable 的结果,而不是将 this.surface 重新定义为 observable 本身
    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 2021-02-21
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 1970-01-01
      相关资源
      最近更新 更多