问题
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