在观察到的内容已订阅时轻按

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

是否有办法向已订阅的可观察对象添加更多操作?我尝试了以下代码,由于未执行订阅后再点击一次部分(代码为here

,该代码不起作用
import { of, timer } from 'rxjs';
import { tap, map, take } from 'rxjs/operators';

const source = timer(1000, 1000);
//transparently log values from source with 'do'
const example = source.pipe(
  take(3),
  tap(val => console.log(`BEFORE MAP: ${val}`)),
  map(val => val + 10),
  tap(val => console.log(`AFTER MAP: ${val}`))
);

//'do' does not transform values
//output: 11...12...13...14...15
const subscribe = example.subscribe(val => console.log(val));

example.pipe(
  tap(val => console.log(`One more tap after subscribe: ${val}`))
);

例如,我想到的使用cas是在这里进行http调用,并且需要通过调用的响应来更新多个服务。

rxjs rxjs6
1个回答
0
投票

我不确定您要实现的目标,但是pipe()函数不会更改源Observable。它只是输出一个新的Observable,它是由旧的和您在管道中使用的运算符产生的。因此,您的最后一行代码就像编写

5;

意味着您将值设置为语句。我不知道在转换后是否可以将Observable分配给它自己而没有副作用(尽管我可以确定,它看起来很丑陋,别人很难理解,因此应该避免)。

example = example.pipe(
  tap(val => console.log(`One more tap after subscribe: ${val}`))
);

也许您应该更详细地说明您的特定用例,以便我们找到更清洁的解决方案。

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