I am working on Angular 6 with Rxjs 6 while I have a question regarding returning a null/empty Observable if response failed or has exception, Here is my assumption, my remote api will return an object of IOptionResponse, it contains a message string which could be indicated like 'SUCCESS' or 'FAILED', it also contains a model which is an array of 'IOption' object
export interface IOptionResponse {
message: string;
model: IOption[];
}
Here is my service method name, it will return a Observable of IOption array which is the "model" of my remote API result
loadIOptionMembersRelationship(): Observable<IOption[]> {
return this.httpClient.get<IOptionResponse>('${environment.apiUrl}/api/member/XXX')
.map(
(response) => {
console.log(response);
// if response.message is success, return IOption[] model
if (response.message == responseMessage.Success) {
return response.model;
}
else {
// return Observable.empty<IOption[]>(); failed
// return new Observable.empty<IOption[]>(); failed
// return new EmptyObservable<IOption[]>(); failed
// return new Observable<IOption[]>.from([]); failed
// Otherwise return a NULL/EMPTY Observable
//What should be the correct way to implement here???
}
}
);
}
I've read the post here which is similar, however I tried all the possible solution and they do not work, I am not sure if it's because that posted solutions are out of date or maybe some method changed in rxjs 6 or maybe it's a typescript issue...
return nullwill complete the observable with a null value. If you want to terminate the observable empty in the case of an error, you should be using flatMap or switchMap or similar, where it would be simplyempty()to terminate the observable without returning anything, orof(null)to return a null value.