I am trying to return an error message from my service that makes an API call to my component that displays the data.
My service gets data like this:
getResults(searchurl: string): Observable<IPageSpeedResult> {
return this._http.get(pageSpeedApiUrl)
.map((response: Response) => this.buildResult(response.json()))
.do(data => console.log(data))
.catch((err:Response) => this.handleError(err));
}
I found this answer that talks about how to do it:
Delegation: EventEmitter or Observable in Angular2
So I added these properties to my service:
private _errorReplaySource : ReplaySubject<string> = new ReplaySubject<string>()
public errorReplay : Observable<string> = this._errorReplaySource.asObservable();
Then in my error handling method I called next() on the _errorReplaySource
private handleError(error: Response) {
this._errorReplaySource.next("There was an error retreiving data for that URL. Please check it is correct and try again.")
return Observable.throw(error.json().error || 'Server error');
}
And then in my component I subscibed a property to it:
ngOnInit(): void {
this._errorSub = this._pageSpeedService.errorReplay.subscribe(error => this.errorMessage = error);
Observable.combineLatest(
this._pageSpeedService.getMessageData(),
this._pageSpeedService.getResults(this.testUrl)
).subscribe(
results => {
this.messageData = <TestResultMessageLogic[]>results[0];
this.testResults = results[1];
this.processApiResponse(this.testResults, this.messageData);
}
)
}
In my template I am using {{errorMessage}}
but when an error occurs the message is not being passed. I am wondering if I this is even the right technique and what I am doing wrong.
Can someone provide me some advice or a simple example of passing the error message?