![](/img/trans.png)
[英]RxJS - How Subscriber is different from Observable and Subscription?
[英]How to Check for a NULL Result from an Angular 5 RxJS Observable during Subscription?
使用Angular中的RxJS Observables
this.myService.getEmp(personEmpId).subscribe(
result => {
this.personName = result.person_name;
},
error => {
console.log("EE:",error);
}
);
如何測試我對該服務的訂閱是否返回NULL結果,即根本找不到記錄?
我嘗試添加錯誤部分,但這沒有觸發控制台消息。
此刻,我似乎收到以下錯誤消息:
ERROR TypeError: "result is null"
您可以在訂閱服務之前添加過濾器,如下所示:
// 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);
}
);
而且,如果您想在Web服務不返回任何內容時添加一些功能,則可以在成功回調中執行以下操作:
this.myService.getEmp(personEmpId)
.subscribe(
result => {
if (result) {
this.personName = result.person_name;
} else {
// do something
}
},
error => {
console.log("EE:",error);
}
);
如果您的方法返回NULL
(未找到記錄),則這不是錯誤。 仍然是有效的回應。 因此將不會執行error
回調。 相反,您應該只在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);
}
);
您可以使用filter
運算符過濾掉NULL結果。
this.myService.getEmp(personEmpId).filter(emp => emp !== null).subscribe..
現在,訂閱者將僅在有值時訂閱。
嘗試這個。
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.