[英]How to continue catchError in timer (rxjs)
我有一个服务,负责使用计时器每 x 秒执行一次 httpClient.get。 我需要这个计时器在服务启动时开始运行,因此计时器在服务构造函数中定义。 根据我的理解,订阅应该在计时器范围内注册,如下所示(如果不需要,我不想更改它,除非它不正确)。
只要后端服务器没有错误\\异常\\错误 500 异常,所有系统都可以正常工作。 现在,我需要两件事:
public IActionResult getSomeErrorAsTest()
{
try
{
throw new Exception("Serer error");
}
catch(Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, new List<string>());
//throw ex;
}
}
这是服务(假设每个 get 请求中的数据都发生了变化——如果确实发生了,则无需实施):
export class MyService
{
MyDataSubject = new Subject<any[]>();
MyDataChanged :Observable>any[]> = this.MyDataSubject.asObservable();
subscribe :Subscription;
constructor(private httpClient : HttpClient)
{
this.subscribe = timer(0, 30000).pipe(
switchMap(()=>
this.getData())).subscribe();
}
getData()
{
return this.httpClient.get<any[]>(<controller url>)
.pipe(
tap(res =>
{
this.MyDataSubject.next(res);
}),
catchError(error =>
{
debugger;//I would expect to catch the debugger here, but nothing happens
return throwError(error);
})
)
}
}
消费者组件:
export class MyComponent (private mySrv : MyService)
{
getMyData()
{
let sub =this.mySrv.MyDataChanged.subscribe(result => doSomething(),
error=> popUpAlert());
}
}
CatchError
运算符允许处理错误,但不会改变 observable 的性质 - 错误是给定 observable 的最终条件,因此发射将停止。CatchError
允许在发生时发出期望值,而不是引发观察者的错误回调( metasong )。
您可能希望处理内部 Observable 中的错误(即内部switchMap
),因此在那里抛出的错误不会冒泡到主流,这样在发生错误后主流会继续,如下所示:
this.subscribe = timer(0, 30000)
.pipe(
switchMap(() => this.getData().pipe(catchError(x => of("handle error here"))))
// catchError(...) don't handle error here
)
.subscribe();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.