Evaluate subscription callback at time observable is created

孤街醉人 提交于 2020-01-17 15:49:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!