Guy*_*y E 4 timer rxjs angular rxjs-observables rxjs-pipe
我有一个服务负责使用计时器每 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;
}
}
Run Code Online (Sandbox Code Playgroud)
这就是服务(假设每个 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);
})
)
}
}
Run Code Online (Sandbox Code Playgroud)
消费者组件:
export class MyComponent (private mySrv : MyService)
{
getMyData()
{
let sub =this.mySrv.MyDataChanged.subscribe(result => doSomething(),
error=> popUpAlert());
}
}
Run Code Online (Sandbox Code Playgroud)
CatchError运算符允许处理错误,但不会改变可观察值的性质 - 错误是给定可观察值的终止条件,因此发射将停止。CatchError允许在发生时发出期望值,而不是引发观察者的错误回调(metasong)。
您可能想要处理内部 Observable (即 inside switchMap)中的错误,因此在那里抛出的错误不会冒泡到主流,这样主流在发生错误后会继续,如下所示:
this.subscribe = timer(0, 30000)
.pipe(
switchMap(() => this.getData().pipe(catchError(x => of("handle error here"))))
// catchError(...) don't handle error here
)
.subscribe();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2364 次 |
| 最近记录: |