我想爲錯誤處理程序創建一種攔截器。這就是爲什麼我創建的文件: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