RXJS - Check data before subscribe
I want to implement a generic HTTP helper
for an Angular project. The backend retuns all Get
responses with this schema :
{
data: any[]; // response data
status:string; // response status , [ ok , problem ]
message:string; // error message
}
I implemented the generic get helper as follow
get<T>(endPoint): Observable<T> {
this.notifier.notify('info', 'Loading ...');
return this.http.get(endPoint).pipe(
map((o) => o.data),
catchError((err) => {
this.notifier.notify('error', err);
return throwError(err);
})
) as Observable<T>;
}
The HTTP errors will catch by catchError
, so the notifier
service will show the error.
For custom errors, I don't know how to catch them in this code and show the error (if statusis
problem`, also I don't want to handle this error after subscribing).
Solution 1:
You could use tap
which is used for handling side effects actions, in this case, for handling the response's status if it is a problem
:
get<T>(endPoint: string): Observable<T> {
this.notifier.notify('info', 'Loading ...');
return this.http.get(endPoint)
.pipe(
tap((response) => {
if (response.status === 'problem') {
// do something with it
}
}),
map((o) => o.data),
catchError((err) => {
this.notifier.notify('error', err);
return throwError(err);
})
); // no need of .asObservable<T>, any http calls return an observable
// if you hover over your get function, you will see that the return
// type is already Observable<T>
}
}
Solution 2:
this should work:
get<T>(endPoint): Observable <T> {
this.notifier.notify('info', 'Loading ...');
return this.http.get(endPoint).pipe(
map(o => {
if (o.status !== 'ok') {
throw 'problem in request status';
}
return o.data;
}),
catchError((err) => {
this.notifier.notify('error', err);
return throwError(err);
})
) as Observable<T>;
}