环境:
我编写了一个名为“ getStatus $”的函数来模拟异步promise,并将其变为可观察的。
当我订阅它时,它工作正常。
但是我将其放入管道中,这是行不通的。
出什么问题了?
如何解决?
谢谢〜
const { from, interval } = rxjs
const { switchMap } = rxjs.operators
const getStatus$ = () => from(new Promise(res => {
setTimeout(() => {
res('zdl')
}, 1000);
}));
// 1s
// 'first zdl'
// It works
getStatus$().subscribe(str => console.log('first', str));
// It doesn't work
// nothing output
interval(1000).pipe(
switchMap(getStatus$)
).subscribe(str => console.log('second', str));
<script src="https://cdn.bootcss.com/rxjs/6.2.0/rxjs.umd.min.js"></script>
感谢Fan Cheung,有两种方式:
interval(1000).pipe(
mergeMap(getStatus$)
).subscribe(str => console.log('second', str));
// or
const getStatus$ = () => from(new Promise(res => {
setTimeout(() => {
res('zdl')
}, 500);
}));
答案 0 :(得分:0)
感谢Fan Cheung,有两种方式:
方法1,使用mergeMap
运算符替换switchMap
:
const { from, interval } = rxjs
const { mergeMap } = rxjs.operators
const getStatus$ = () => from(new Promise(res => {
setTimeout(() => {
res('zdl')
}, 1000);
}));
interval(1000).pipe(
mergeMap(getStatus$)
).subscribe(str => console.log('second', str));
<script src="https://cdn.bootcss.com/rxjs/6.2.0/rxjs.umd.min.js"></script>
方法2,使getStatus$
的时间比interval
短,我将其更改为500ms:
const { from, interval } = rxjs
const { switchMap } = rxjs.operators
const getStatus$ = () => from(new Promise(res => {
setTimeout(() => {
res('zdl')
}, 500);
}));
interval(1000).pipe(
switchMap(getStatus$)
).subscribe(str => console.log('second', str));
<script src="https://cdn.bootcss.com/rxjs/6.2.0/rxjs.umd.min.js"></script>