Rxjs从初始源开始多次操作数据

时间:2017-10-15 10:07:27

标签: rxjs

我有一个Observable,我想从同一个源操作两次数据而不修改下一个数据。

我的意思是如果我使用两次.map(),第一次修改数据,第二次修改数据。我不想要那个。

很抱歉,我确定可以在StackOverflow中找到答案,但我不能用我的话找到答案,而且我不了解Rxjs doc中的模式。

更新

this.anObservable
  .map((data) => { 
      // Here we manipulate and save formatted data in variable 'resume'
      this.resume = this.doSomething(data) 
  })
  // Here I want to send data to another function, but that send the formatted data and not de initial data
  .map((data) => this.doOtherThing(data));

同样:

this.anObservable
  .map((data) => { 
      this.resume = this.doSomething(data);
      this.doOtherThing(data);
  })

更新2

/** This doesn't work : */

this.anObservable
      .do((data) => { 
          // Here we manipulate and save formatted data in variable 'resume'
          this.resume = this.doSomething(data) 
      })
      // Here I want to send data to another function, but that send the formatted data and not de initial data
      .map((data) => this.doOtherThing(data));

我也试过变量:

private dataToFormat;

this.anObservable
      .do((data) => {
          this.dataToFormat = data;

          // let dataToFormat = data;
          this.resume = this.doSomething(this.dataToFormat) 
      })
      // Here I want to send data to another function, but that send the formatted data and not de initial data
      .map((data) => this.doOtherThing(data));

更新3

我有服务:

  // Sources
    private formData = new Subject<any>();
    // Streams
    public formData$ = this.formData.asObservable();

    public setData (request: any): void {
        this.formData.next(this.removeEmptyObjectsAndFormatDate(request));
    }

然后我订阅了它:

 this.service.formData$
          .do((data) => {
              this.resume = this.doSomething(data) 
          })
          // Here I want to send data to another function, but that send the formatted data and not de initial data
          .map((data) => this.doOtherThing(data));

没有人有答案?

1 个答案:

答案 0 :(得分:0)

如果您只是想做某事而不是转换数据,则可以使用.do()。在反应式编程中,这就是我们所说的#34;没有副作用&#34;。

但是,请注意,在JavaScript中,对象是通过引用传递的,因此对对象的任何操作实际上都会操纵对象。你想要做的是创建它的浅表副本,然后操纵它,然后保存它。

您可以通过Object.assign()方法轻松实现此目的:

this.anObservable
    .do((data) => {
        let newCopyOfData = Object.assign({}, data);
        this.resume = this.doSomething(newCopyOfData);
    })
    // the data here wont get changed
    .map((data) => this.doOtherThing(data));