简体   繁体   中英

How to Check for a NULL Result from an Angular 5 RxJS Observable during Subscription?

With RxJS Observables within Angular

this.myService.getEmp(personEmpId).subscribe(
        result => {
            this.personName = result.person_name;
        },
        error => {
            console.log("EE:",error);
        }
    );

How can I test if my subscription to this service returns a NULL result, ie no record was found at all?

I tried adding the error part but this did not fire the console message.

At the moment, I seem to be getting the following error message:

ERROR TypeError: "result is null"

You can add a filter before subscribing to your service like this:

// add this import on top of your source file
import { filter } from 'rxjs/operators'

this.myService.getEmp(personEmpId)
    .pipe(filter(result) => !!result)
    .subscribe(
        result => {
            this.personName = result.person_name;
        },
        error => {
            console.log("EE:",error);
        }
);

And if you want to add some feature when your webservice doesn't return anything, you can do it in your success callback like this:

this.myService.getEmp(personEmpId)
    .subscribe(
        result => {
            if (result) {
                this.personName = result.person_name;
            } else {
                // do something
            }
        },
        error => {
            console.log("EE:",error);
        }
);

If your method is returning NULL (No records found), then that is not an error. It is still a valid response. So error call back won't be executed. Instead you should handle this special scenario inside success callback only

this.myService.getEmp(personEmpId).subscribe(
    result => {
        if(result){ 
           this.personName = result.person_name;
        }
        else {
           //log or display no data found message
        }
    },
    error => {
        console.log("EE:",error);
    }
);

You can filter out the NULL results using the filter operator.

this.myService.getEmp(personEmpId).filter(emp => emp !== null).subscribe..

Now the subscriber will subscribe only when there are values.

Try this.

this.myService.getEmp(personEmpId).subscribe(
        result => {
            if(result){
                 this.personName = result.person_name;
            }
            else{
              //error code
            }
        },
        error => {
            console.log("EE:",error);
        }
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM