我想为错误处理程序创建一种拦截器。这就是为什么我创建的文件:Angular没有看到注入的服务
ErrorService:
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;
}
}
AppErrorHandler:
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
突然Angulas看不到它。
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
显示它并没有看到传递的数据
UPDATE: 我也跟着下面的解决方案,并得到一个错误。我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控制台我:
所以你可以看到,我可以easliy得到整个对象ErrorService但无法得到的属性名称这在控制台undefined
- 为什么?正因为如此,我无法正确显示它。
问题在哪里?你得到了什么样的错误? –
将'ErrorService'注入'AppErrorHandler'时,不要使用'@Inject'。 @Inject用于原始值/类型。只要执行'constructor(private errorService:ErrorService){}'。看看这是否有所作为。 –
问题是在'AppErrorHandler'中,我将错误传递给'ErrorService',我想将它显示在'ErrorComponent'中,但是'ErrorComponent'没有看到传递的数据 – bielas