我有一个从http
获取json的服务我在主应用程序中创建了一个错误对话框,但我不明白你如何将可能的错误交还给applicationi,以便将它显示在网页上
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 ?
},
);
}
}
感谢
答案 0 :(得分:1)
我会实现自定义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 {}
然后在错误对话框组件中:
class ErrorDialog implements OnInit {
constructor(private errorHandler: MyErrorHandler) {
}
ngOnInit() {
this.errorHandler.errorEvent$.subscribe(t=> {
// show dialog here
});
}
}