2
假设我有函数使http调用并返回Observable与用户的详细信息。如何延迟发出错误的Observable
如果用户不存在,则返回发出错误的Observable。
// Get user by id
function getUser(id) {
return Rx.Observable.create(obs => {
if (id === 1) {
obs.next('200 - User found');
obs.complete();
} else {
obs.error('404 - User not found');
}
});
}
// This will print "200 - User found" in the console after 2 seconds
getUser(1)
.delay(2000)
.subscribe(r => console.log(r));
// !!! Delay will not work here because error emmited
getUser(2)
.delay(2000)
.subscribe(null, e => console.log(e));
有什么办法来延迟可观察到发射错误?
你为什么推迟呢? –
我想延迟对API的每个http请求,无论成功与否(测试应用程序在响应太长时如何表现) –
您正在编写测试吗?你通常应该使用浏览器网络选项卡节流功能来模拟长请求 –