为什么返回interval(500)
会在下面的代码中抛出以下类型错误?
const source = timer(0, 5000);
const example = source.pipe(switchMap(() => interval(500)));
const subscribe = example.subscribe(val => console.log(val));
类型为'UnaryFunction <Observable <number>的参数,Observable <number >>'不能分配给'OperatorFunction'类型的参数。
参数'source'和'source'的类型不兼容。
类型'Observable <any>'不能分配给'Observable <number>'。
属性'source'受保护,但类型'Observable <T>'不是从'Observable <T>'派生的类。
这是在learnrxjs.io上找到的第一个switchMap example。
问题是timer
被定义为发出数值。因此,source
也会假设将发出数值。然而,switchMap
没有假设返回的可观测量将发出什么类型(因此any
)。这意味着你的来源从发射数字到发射任何东西。
这是一个简单的解决方案
import { timer, interval } from 'rxjs';
import { switchMap } from 'rxjs/operators';
//emit immediately, then every 5s
const source = <any>timer(0, 5000); //Here, we say that source can emit anything
//switch to new inner observable when source emits, emit items that are emitted
const example = source.pipe(switchMap(() => interval(500)));
//output: 0,1,2,3,4,5,6,7,8,9...0,1,2,3,4,5,6,7,8
const subscribe = example.subscribe(val => console.log(val));