我有一个关于可观测数据的优化问题:
我有两个接受用户名和密码的控件。当密码字段的值发生变化时,我想调用一个服务方法,该方法返回一个可观察到的查询结果,然后用这些值填充模型。
如果出现服务错误,返回的可观测值将抛出异常。但在这种情况下,我只想用一个空数组填充模型。
我最初的实现是:
this.passwordControl.valueChanges
.debounceTime(500)
.filter(_ => this.usernameControl.valid && !this.usernameControl.pristine)
.map((password) => new RequestAuthentication(this.usernameControl.value, password))
.mergeMap(auth => this.orgService.getOrganizations(auth))
.catch(_ => {
return Observable.of([]);
})
.subscribe(orgs => {
this.organizations = orgs;
});缺点是,在执行catch函数时,我返回一个有限的可观察到的流,并且我不能再听这些更改了。
我的解决办法是将可观察到的物体嵌套成这样:
this.passwordControl.valueChanges
.debounceTime(500)
.filter(_ => this.usernameControl.valid && !this.usernameControl.pristine)
.map((password) => new RequestAuthentication(this.usernameControl.value, password))
.subscribe(auth => {
this.orgService.getOrganizations(auth)
.catch(_ => Observable.of([]))
.subscribe(orgs => {
this.organizations = orgs;
});
});但这似乎不是很有反应..。我应该如何避免这些嵌套的可观察性,并保持代码的干净?
发布于 2017-05-16 12:27:51
通常,不建议在另一个subscribe()中调用subscribe(),因为您只是将“回调地狱”与“订阅地狱”交换。而且,您正在从父可观测链中丢失error和complete信号。尽管如此,你还是可以避免的。
因此,如果您不想在发生错误时终止链,那么有几个操作符可以帮助您。特别是:retry()和retryWhen() (也是onErrorResumeNext()),可能还有更多。
如果您不想在错误信号发生时做任何事情,请使用retry()而不是catch()
.mergeMap(...)
.retry()
.subscribe(orgs => {
this.organizations = orgs;
});如果您仍然希望能够执行某些副作用(通知用户或其他什么),请在.do()之前使用retry()。
.mergeMap(...)
.do(null, e => ...)
.retry()
.subscribe(orgs => {
this.organizations = orgs;
});https://stackoverflow.com/questions/44000787
复制相似问题