我想为错误处理程序创建一种拦截器。这就是我创建文件的原因:
错误服务:
import { Injectable } from '@angular/core';
@Injectable()
export class ErrorService {
name : any;
constructor() {
}
setName(message:string){
this.name = message;
}
getName(){
return this.name;
}
error(detail: string, summary?: string): void {
this.name = detail;
}
}
应用程序错误处理程序:
import { ErrorService } from './error-service';
import { ErrorHandler, Inject } from '@angular/core';
export class AppErrorHandler implements ErrorHandler {
constructor(@Inject(ErrorService) private errorService: ErrorService){
}
handleError(error : any){
this.errorService.setName(error.status);
console.log('getter', this.errorService.getName());
console.log('test error ', error);
}
}
到那时,一切都很顺利。当我在
handleError
中打印错误时它打印正确。但是当我想通过
ErrorService
对象进入 ErrorComponent
突然安古拉斯看不见了。错误组件:
import { ErrorService } from './../common/error-service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'error',
templateUrl: './error.component.html',
styleUrls: ['./error.component.css']
})
export class ErrorComponent implements OnInit {
constructor(private errorService: ErrorService) {
console.log('from ErrorComponent, ', this.errorService);
}
message = this.errorService.getName();
ngOnInit() {
}
}
和 ErrorComponent.html
<div class="alert alert-danger">
Error!!! {{message}}
</div>
当然,我在
app.module
中添加了一些导入。 :import { ErrorComponent } from './error/error.component';
@NgModule({
declarations: [
...
ErrorComponent
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpModule
],
providers: [
PostService,
ErrorService,
{provide: ErrorHandler, useClass: AppErrorHandler}
],
bootstrap: [AppComponent]
})
export class AppModule { }
问题是在
AppErrorHandler
我将错误传递给 ErrorService
我想在 ErrorComponent
中显示它但是 ErrorComponent
没有看到传递的数据更新:
我遵循以下解决方案并得到一个错误。我的
errorComponent
好像:import { ErrorService } from './../common/error-service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'error',
templateUrl: './error.component.html',
styleUrls: ['./error.component.css']
})
export class ErrorComponent implements OnInit {
errorService: ErrorService;
message: string;
constructor(errorService: ErrorService) {
this.errorService = errorService;
console.log('------ from error component ', errorService.name, this.errorService);
}
ngOnInit() {
}
}
和
html
文件:<div class="alert alert-danger">
Error!!! {{errorService.name}}
</div>
问题是我实际上无法在浏览器中打印 name 属性。在 chrome 控制台中,我有:
因此您可以看到我可以轻松获取整个对象 ErrorService 但无法获取控制台中为
undefined
的属性名称- 为什么?因此,我无法正确显示它。
最佳答案
以下是解决您的问题的方法:
1) 能够有效注入(inject)ErrorService
进入 AppErrorHandler
,你会想要装饰AppErrorHandler
与 Injectable()
.有了它,您可以删除 @Inject(ErrorService)
并以标准方式简单地注入(inject)服务。
import { ErrorService } from './error-service';
import { ErrorHandler, Injectable } from '@angular/core';
@Injectable()
export class AppErrorHandler implements ErrorHandler {
constructor(private errorService: ErrorService){}
}
2) 在
AppErrorHandler
您的目标是一个属性 status
的错误对象。请记住,标准错误对象具有 message
等属性。 , name
, description
, 和 number
取决于浏览器。您可能需要检查 status
属性在尝试获取它的值之前存在,否则你可以获得 undefined
对于非 HTTP 错误。更新:请务必调用
super(true);
和 super.handleError(error);
或 throw error;
以确保错误被重新抛出,并且在您的自定义错误处理之后发生默认错误处理。否则错误将被自定义错误处理程序吞下。导出类 AppErrorHandler 实现 ErrorHandler {
// ...
handleError(error : any) {
// rethrow exceptions
super(true);
if(error.status) {
console.log(error.status);
this.errorService.setName(error.status);
}
else {
console.log('Message: ', error.message);
console.log('Description: ', error.description);
this.errorService.setName(error.message);
}
console.log('Getter: ', this.errorService.getName());
// trigger default error handling after custom error handling
super.handleError(error);
}
}
3) 在您的错误组件中,主动查看对
name
的更改ErrorService
的属性(property),您至少要制作 name
属性(property)公共(public)属性(property)。然后在 ErrorComponent 中,您将针对注入(inject)服务的 name
要显示的属性。例如,一种更具可扩展性的方法是使用 RxJS Subject 来发出 ErrorComponent
的更改。可以订阅。做message = this.errorService.getName();
发生错误时,不会自动重置/响应对 name 属性的更改。您需要附加到公共(public)属性和/或使用 observables 或类似的东西来对要订阅的组件进行更改。见 更新 2 下面以如何使用 RxJS 为例进行更新 message
.服务:
import { Injectable } from '@angular/core';
@Injectable()
export class ErrorService {
public name : any;
constructor() {}
错误组件 HTML
<div class="alert alert-danger">
<!-- Angular will detect changes to the services' -->
Error!!! {{errorService.name}}
</div>
这是 plunker演示功能。单击按钮触发错误,在这种情况下调用不存在的方法。
更新:
console.log('------ from error component ', errorService.name, this.errorService);
在构造函数中记录 undefined
因为当时constructor()
运行,公共(public)属性(property)name
没有默认值。如果你想要一个默认值,你可以在 ErrorService
中设置它。做public name: string = 'foobar';
. plunker已更新以显示 name
之前和之后的日志记录的 ErrorService
正在设置。如果在 ErrorService
中添加默认值你会看到你的日志,打印name
适当的值(value)。更新 2:如果你绝对需要使用
message
在 ErrorComponent
而不是用于显示值的任何其他属性,包括 ErrorService
的公众 name
属性,您可以使用 Subject 和 Observable 订阅发出的更改以更新类似于 Parent/Child Interaction 的 name 属性.这将涉及在 ErrorService
上实例化一个新主题。 ,公开可观察的公共(public)属性(property)并订阅这些更改。这显示了如何专门使用message
ErrorComponent
的属性(property)从 ErrorService
获取值它是 name
属性(property)。如果唯一的目标是在 ErrorComponent
中显示错误,您可能并不真的需要 name 属性。 .另外在 plunker ,它在 message
中显示 HTTP 错误状态代码ErrorComponent
的属性(property).@Injectable()
export class ErrorService {
public name: string;
// create new Subject
private nameSource = new Subject<any>();
// expose Observable property
error$ = this.nameSource.asObservable();
setName(message: string){
this.name = message;
// emit error
this.nameSource.next(this.name);
}
// ...
}
@Component({ // ... })
export class ErrorComponent {
message: string = '';
constructor(private errorService: ErrorService) {
// same stuff as before
// subscribe to Observable from ErrorService and update name property on changes
this.errorService.error$.subscribe(name => {
this.message = name;
});
}
}
@Injectable()
export class AppErrorHandler extends ErrorHandler {
private errorService: ErrorService;
constructor(errorService: ErrorService) {
super(true);
this.errorService = errorService;
console.log(this.errorService);
}
handleError(error : any) {
if(error.status) {
console.log(error.status);
this.errorService.setName(error.status);
}
else {
console.log('Message: ', error.message);
console.log('Description: ', error.description);
this.errorService.setName(error.message);
}
}
}
这是更新的 plunker .
希望这会有所帮助!
关于Angular 看不到注入(inject)的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45623417/