Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a null/empty Observable in Angular 6 with Rxjs 6

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...

like image 489
Kev D. Avatar asked Dec 11 '22 05:12

Kev D.


2 Answers

If you want to return an empty Observable array while using Rxjs6, you need to...

import { of } from 'rxjs';

Then where you want to return your empty Observable array of <IOption[]> type ...

return of<IOption[]>([]);
like image 98
Pooshon Banerjee Avatar answered Mar 02 '23 19:03

Pooshon Banerjee


Do you care about FAILED results? If you do not (which is quite true since you want to emit an empty Obersavble), you can just simply filter it. Then you do not need to explicitly emit an empty Observable:

 loadIOptionMembersRelationship(): Observable<IOption[]> {
    return this.httpClient.get<IOptionResponse>('${environment.apiUrl}/api/member/XXX')
        .filter(response => response.message === responseMessage.Success) //only emit those response whose message is SUCCESS
        .map(response => response.model);
}

Explicitly returning an empty Observable will terminate the stream, which may or may not be what you want depending on your implementation.

like image 22
CozyAzure Avatar answered Mar 02 '23 19:03

CozyAzure