[英]How to Check for a NULL Result from an Angular 5 RxJS Observable during Subscription?
With RxJS Observables within Angular 使用Angular中的RxJS Observables
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? 如何测试我对该服务的订阅是否返回NULL结果,即根本找不到记录?
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: 而且,如果您想在Web服务不返回任何内容时添加一些功能,则可以在成功回调中执行以下操作:
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. 如果您的方法返回NULL
(未找到记录),则这不是错误。 It is still a valid response. 仍然是有效的回应。 So error
call back won't be executed. 因此将不会执行error
回调。 Instead you should handle this special scenario inside success
callback only 相反,您应该只在success
回调中处理这种特殊情况
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. 您可以使用filter
运算符过滤掉NULL结果。
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);
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.