简体   繁体   English

动态参数 startWith Rxjs

[英]Dynamic parameters startWith Rxjs

I wish to addition emmited values of multiples input fields when a values changes.我希望在值更改时添加多个输入字段的发射值。

The problem is : There is multiple fields and i wish it dynamic because i don't know how many fields i can have in advance !问题是:有多个字段,我希望它是动态的,因为我不知道我可以提前拥有多少个字段!

// In this case i have 3 input fields 
var keyObjectFields = ["0", "1", "2"];


const observedValues = keyObjectFields.map(key => this.credentialsForm.controls[key].valueChanges
    .map(value => +value).startWith(0, 0, 0))

const resSurface = combineLatest(observedValues)
    .pipe(map(([value0, value1, value2]) => { return value0 + value1 + value2 }));

resSurface.subscribe(val => { this.surface = val });

Use startWith(0) to start each observable with 0. Use array.reduce to calculate the sum of an array.使用startWith(0)开始观察到的每个具有0。使用array.reduce来计算阵列的总和。

// In this case i have 3 input fields 
var keyObjectFields = ["0", "1", "2"];


const observedValues = keyObjectFields.map(
  key => this.credentialsForm.controls[key].valueChanges.pipe(
    map(value => +value),
    startWith(0)
  )
);

const resSurface = combineLatest(observedValues).pipe(
  map(values => values.reduce((sum, curr) => sum + curr))
);

resSurface.subscribe(val => { this.surface = val });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM