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

自古美人都是妖i 提交于 2021-02-18 15:04:14

问题


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, i.e. 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"

回答1:


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);
        }
);



回答2:


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);
    }
);



回答3:


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.




回答4:


Try this.

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


来源:https://stackoverflow.com/questions/51421683/how-to-check-for-a-null-result-from-an-angular-5-rxjs-observable-during-subscrip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!