Angular 角度RxJS-无法使冷变热

Angular 角度RxJS-无法使冷变热,angular,rxjs,observable,operators,Angular,Rxjs,Observable,Operators,代码: const cold=新的可观察对象((观察者:观察者)=>{ observer.next(Math.random()); }); const hot=cold.pipe(share()); hot.subscribe(a=>console.log('a:'+a)); hot.subscribe(b=>console.log('b:'+b)); } 预期结果-a和b具有相同的值: //a:0.17919353301075858 //b:0.17919353301075858 实际结果-

代码:

const cold=新的可观察对象((观察者:观察者)=>{
observer.next(Math.random());
});
const hot=cold.pipe(share());
hot.subscribe(a=>console.log('a:'+a));
hot.subscribe(b=>console.log('b:'+b));
}

预期结果-a和b具有相同的值:

//a:0.17919353301075858

//b:0.17919353301075858

实际结果-仅在浏览器控制台中获取a的值:

//a:0.07958207844185083


有什么想法吗?

您可以尝试
shareReplay(1)
重播上一个值


另外,还有一篇好文章:

您可以使用热可观测值,如
interval
map
操作符

从'rxjs'导入{interval};
从“rxjs/operators”导入{map};
const source=interval(1000).pipe(map(()=>Math.random());
constsubscribe=source.subscribe(val=>console.log(val));

这是否回答了您的问题?“热可观测”是指不断发出值(如interval)或dom事件(如mouse move)且从未完成的对象,我认为您只想重播上一个值检查此值在您的案例中不相同(如所需)+缺少两个“订阅”,那么使用
ReplaySubject
Yes,已经有了一些有用的预定义操作符。查看我答案中的文章-非常有用的一篇
const cold = new Observable((observer: Observer<any>) => {
  observer.next(Math.random());
});

const hot = cold.pipe(share());
hot.subscribe(a =>  console.log('a: ' + a));
hot.subscribe(b =>  console.log('b: ' + b));