Reputation:
I have a service that gets a json from http
I created a dialog for errors in my main app, but I dont understand how you give back the potential error to the applicationi so it displays it on the web page
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class TranslateService
{
constructor(private http:Http)
{
this.http.get("some.json").map(res => res.json())
.subscribe(
res =>
{
....
},
error =>
{
console.log(error); <<<< how to give this error to the main application component ?
},
);
}
}
thanks
Upvotes: 1
Views: 283
Reputation: 52837
I would implement a custom global error handler:
class MyErrorHandler implements ErrorHandler {
private errorSubject:Subject<any>;
public errorEvent$: Observable<any>;
constructor() {
this.errorSubject = new Subject<any>();
this.errorEvent$ = this.errorSubject.asObservable();
}
handleError(error) {
// do something with the exception
this.errorSubject.next(error);
}
}
@NgModule({
providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
})
class MyModule {}
Then in your error dialog component:
class ErrorDialog implements OnInit {
constructor(private errorHandler: MyErrorHandler) {
}
ngOnInit() {
this.errorHandler.errorEvent$.subscribe(t=> {
// show dialog here
});
}
}
Upvotes: 1