传递更多值以订阅可观察对象的功能 [英] Pass more values to subscribe function of an observables

查看:79
本文介绍了传递更多值以订阅可观察对象的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用对象的方法转换并替换数组中的所有单词,该方法返回一个可观察值.问题在于,由于结果是异步的,因此在错误的索引处错误地覆盖了结果的值.如果我有一个同步函数,我可以简单地在for循环中调用该函数.在这种情况下我该怎么办?

I would like to convert and replace all words in an array using a an object's method which returns an observable. The problem is that since the result is asynchronous, the value of result is overwritten incorrectly at the wrong index. If I had a synchronous function, I could have just simply call the function in a for loop. What should I do in this case?

 for(let word in this.words){
        var i = Object.keys(this.words).indexOf(word);

        this.convertor.get(this.words[i].value).subscribe( (result) => {
            this.words[i].value = result; //The value of i is incorrect
        });
    }

推荐答案

您可以使用简单的函数来解决此问题,该函数将一个额外的参数绑定到:

You could solve this with a plain function that you bind an extra argument to:

    this.convertor.get(this.words[i].value).subscribe( function (i, result) {
        this.words[i].value = result; 
    }.bind(this, i));

.bind() 返回一个( new)函数,就像您应用bind的函数一样,但是它将为实际调用该函数时预先确定一些条件:

.bind() returns a (new) function that will be like the function you apply bind on, but will pre-determine a few things for when that function is actually called:

    然后,将
  1. this设置为您在第一个参数中传递给bind的内容.与箭头函数相反,老式函数通常通过调用函数的方式获取其this值-这种行为不是您想要的,因此这是bind;

  1. this will then be set to what you pass to bind in the first argument. Contrary to arrow functions, old-fashioned functions normally get their this value by how the function is called -- that behaviour is not what you desire, and so it is a welcome feature of bind;

某些参数可以预先固定.您通过bind传递的其他任何参数都将成为该函数的第一个参数的值-它们不是由实际调用确定的.在这种情况下,将传递 i 的值,因此该函数将获得该值作为其第一个参数,无论以后如何调用.

Some of the arguments can be fixed upfront. Whatever other arguments you pass via bind become the values of the first arguments of that function -- they are not determined by the actual call. In this case the value of i is passed, so the function will get that value as its first argument, no matter how it is called later.

在调用(返回)时传递给函数的其他任何参数都将遵循前面提到的参数.在这种情况下,实际的调用将传递 result 的值,因此该函数应处理两个参数:一个由bind提供,另一个由调用者提供.

Any other argument that is passed to the function at the moment of the call(back) will follow the previously mentioned arguments. In this case, the actual call will pass the value of result, and so the function should deal with two arguments: one provided by bind, the other by the caller.

这可以解决您的问题,因为您可以将 i 的正确值传递给每个函数,而不会丢失this的值.

This solves your issue as you can pass on the correct value of i to each of the functions without losing the value of this.

这篇关于传递更多值以订阅可观察对象的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆