I am trying to develop an Angular application where there is a situation I am calling a service that is subscribed to HTTP service. I have written an alert prompt service which internally calls the HTTP service when "ok" is pressed. Like this:
this.alertservice.prompt(url);
This will prompt the user for confirmation. If the user clicks "ok", the alert service will call the HTTP service internally:
this.httpservice.get(url).subscribe(res => {
console.log(res);
});
Now I want to inform the parent caller whether the call failed or succeeded. Something like:
this.alertservice.prompt(url).subscribe(res => {
console.log("success or failure");
});
But I am not understanding how to subscribe to the alert function. How do I do this?
maybe something like:
import {..., EventEmitter} from '@angular/core';
export class AlertService {
...
prompt(url:string): Observable<boolean> {
let result = new EventEmitter<boolean();
this.httpService.get(url).subscribe
(
(res) => {
console.log("OK:", res);
result.emit(true);
result.complete();
},
(error) => {
console.log("ERROR:", error);
result.emit(false);
result.complete();
}
);
return result;
}
}
now you can subscribe to the prompt()-function:
this.alertService.promp(url).subscribe((okOrNotOk) => {
// okOrNotOk will be true, when the url was retrieved successfully,
// otherwise false
});
I'm not an expert on rxjs, perhaps there is a better way to do this.