我们如何在 rxjs/map 运算符中使用参数

问题描述 投票:0回答:2

在rxjs,

export function map<T, R, A>(project: (this: A, value: T, index: number) => R, thisArg: A): OperatorFunction<T, R>;

我找不到

thisArg: A
的用法。

javascript typescript rxjs
2个回答
1
投票

这与

Array.prototype.map
中的目的相同:当您将函数作为参数传递时,上下文会丢失。

class Value {
   constructor (public value:number) {}
   addValue (x:number) { return this.value + x; }
}

const five = new Value(5);
[1, 2, 3].map(five.addValue); // Error because this is undefined
[1, 2, 3].map(five.addValue, five); // [6, 7, 8]

RxJS 示例

const source = Rx.Observable.from([1, 2, 3]);

source.map(five.addValue); // NaN...NaN...NaN

source.map(five.addValue, five); // 6...7...8

0
投票

感谢 Geoffrey 的提醒,这是它的 rxjs 版本


import { of } from 'rxjs';
import { map } from 'rxjs/operators';
class Value {
   constructor (value) {
    this.value = value;
   }
   addValue (x) { return this.value + x; }
}

const five = new Value(5);
// Example data
const numbers = [1, 2, 3];
of(...numbers)
  .pipe(
    map(five.addValue, five) // This is the reference to the object having value 5
  )
  .subscribe(transformedData => {
    // Do something with the transformed data
    console.log(transformedData);
  });

© www.soinside.com 2019 - 2024. All rights reserved.