问题
I have a Reactive Form in which it appears the function inside the following subscription evaluates itm["value"].length-1
at the time the observable emits data (and calls the subscription function).
this.formCtls[controlName] = new FormControl('', {updateOn: 'blur'});
this.userForm.addControl(controlName, this.formCtls[controlName]);
this.formCtls[controlName].valueChanges.subscribe(val=>{
itm["value"][itm["value"].length-1]=val;
this.renderDataArray();
});
However I want the subscription callback function expression itm["value"].length-1
to be evaluated at the time the observable/(FormControl) is created.
For instance, at the time the form control is created, itm["value"].length
might only be 2
, but at the time the Observable emits itm["value"].length
may be 6
or 7
or any other number. How can I (programatically) "hardwire" the 2
(or equivalent) into the subscription callback?
Many thanks in advance!
回答1:
I'm not so sure about the answer below now. It worked in my code, but I'm not sure why it worked. I will re-evaluate this provisional answer and post an update. In the meantime, I'd be very grateful for any input from an expert as I'm a bit confused and lost amongst these Observables. . .
this.formCtls[controlName] = new FormControl('', {updateOn: 'blur'});
this.userForm.addControl(controlName, this.formCtls[controlName]);
const idx = itm["value"].length-1;
this.formCtls[controlName].valueChanges.subscribe(val=>{
itm["value"][idx]=val;
this.renderDataArray();
});
来源:https://stackoverflow.com/questions/58244665/evaluate-subscription-callback-at-time-observable-is-created