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"
The RxJS isEmpty() operator returns an observable with a Boolean value indicating whether the observable was empty or not. It returns an output as true if the source observable is empty; otherwise, false.
This call also returns an object, the Subscription : const subscription = observable.subscribe((x) => console.log(x));
import { ReplaySubject } from 'rxjs'; // Tell the compiler there's a isNowEmpty() method declare module "rxjs/ReplaySubject" { interface ReplaySubject<T> { isNowEmpty(): boolean; } } ReplaySubject. prototype['isNowEmpty'] = function() { let events = this. _trimBufferThenGetEvents(); return events.
Subscriptions to observables are quite similar to calling a function. But where observables are different is in their ability to return multiple values called streams (a stream is a sequence of data over time). Observables not only able to return a value synchronously, but also asynchronously.
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);
}
);
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.
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);
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With