单击按钮后,将调用一个http请求:
let saveClickPush$ = Observable
.fromEvent(this.saveButton.nativeElement, 'click')
.pipe(
switchMap(() => this.service.push(this.user)),
share()
);
因此,当单击它时,我将创建两个可观察对象:
this.pushed$ = saveClickPush$.pipe(this.pushUser(), this.handleEmptyUser());
this.error$ = saveClickPush$.pipe(this.handleError<never>());
其中:
private handleError = <T>() => catchError<T, Array<{code: string, message: string}>>((error: ResponseError) => Observable.of(error.errors));
private handleEmptyUser = <T>() => catchError<T, AdministrationUser>(() => Observable.of(UserComponent.EMPTY_USER));
我想做的是当出现错误时:
pushed$
发出了一个空用户。error$
上发出详细的错误消息。但是,当出现http错误时,当我单击按钮时,不会再次调用http请求。尽管我已尝试处理错误,但先前引发HTTP错误时,似乎所有订阅者都已取消订阅。
我的服务是:
public push(user: AdministrationUser): Observable<AdministrationUser> {
const buildURL = () => map((userId: string) => this.buildPushURL(userId));
return Observable.of(user.id)
.pipe(
buildURL(),
switchMap((url: string) => this.http.post(url, user)
.pipe(
map(() => user),
catchError((error: Response) => Observable.throw(<ResponseError>error.json()))
)
)
);
}
因此,当出现http错误时:
Observable.throw
处理error response
。pushed$
上可以观察到,也可以通过答案 0 :(得分:0)
由于您在this.service.push()
流中抛出了错误,为了不中断点击流,您将必须包含并捕获内部可见的错误
let saveClickPush$ = Observable
.fromEvent(this.saveButton.nativeElement, 'click')
.pipe(
switchMap(() => this.service.push(this.user).pipe(catchError(e=>of(e))),
share()
);