Angular2-如何将服务错误返回到主应用程序组件
我有一个从http获取json的服务 我为我的主应用程序中的错误创建了一个对话框,但我不明白你是如何将潜在错误返回给应用程序的,所以它会显示在网页上Angular2-如何将服务错误返回到主应用程序组件,angular,service,Angular,Service,我有一个从http获取json的服务 我为我的主应用程序中的错误创建了一个对话框,但我不明白你是如何将潜在错误返回给应用程序的,所以它会显示在网页上 import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; @Injectable() export class TranslateService { constructor(private http:Http) {
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 ?
},
);
}
}
从'@angular/core'导入{Injectable};
从'@angular/Http'导入{Http};
@可注射()
导出类TranslateService
{
构造函数(专用http:http)
{
this.http.get(“some.json”).map(res=>res.json())
.订阅(
res=>
{
....
},
错误=>
{
console.log(错误);我将实现一个自定义:
你能把你的组件的代码也贴上吗?很好,…顺便说一句,我不明白为什么它被称为观察者,因为它是一个将向流提供数据的组件,而不是一个将订阅和“监听”观察者的组件。什么是@before private?
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
});
}
}