أنجولار - إرجاع نتيجة مرصد باستخدام combineLatest و Rxjs
أتمنى الحصول على نتيجة لمراقب يقوم بطرح القيمة الافتراضية في كل مرة يتغير فيها القيمة
في كل مرة تتغير القيمة، يتم طرح القيمة الافتراضية من القيمة الجديدة المُدخلة في حقل الإدخال
على سبيل المثال، القيمة الافتراضية هي 5.
أدخل 4 في حقل الإدخال
النتيجة هي 5-4=1 لذلك أرغب في عرض 1 في حقل الإدخال "مساحة هكتار"
أقوم بمسح الحقل ثم أدخل 3. النتيجة هي 5-3=2، لذا أرغب في عرض 2 في حقل الإدخال "المساحة هكتار"
وهكذا وهكذا ....
إذا قمت بعمل 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 واستخدام أنبوب async في Angular للربط مباشرة بـ 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;
