0
votes

I already setup such an observable pattern and it usually works, but as I use it in a custom error handler it does not work.

Apparently the code in the constructor never gets executed, but it's a regular class, I can't use onInit , can't I?

edit: I tried putting the code in an init function that gets called from the dialog component before the subscribe, but when an error occurs , handleError gets called, it seems the context has changed and nothing is defined (observer and observable are undefined)

the custom error handler:

export class CustomErrorHandler implements ErrorHandler 
{
   public errors : Observable<Error>;
   private errorsObserver : Observer<Error>;

   constructor() {

       this.errors = Observable.create((observer :Observer<Error>)=>  <<<<<<THIS ONE NEVER GETS EXECUTED
        {
          this.errorsObserver = observer;
       }).share();
   }

  handleError(error:Error) {
    this.errorsObserver.next(error);
  }
}

@NgModule({
  providers: [{provide: ErrorHandler, useClass: CustomErrorHandler}]
})
export class CustomErrorHandlerModule {}

the dialog component:

@Component({
    moduleId: module.id,
    selector: 'dialog',
    templateUrl: './dialog.component.html',
})
export class Dialog implements OnInit
{
    private ErrorMsg: string;
    public ErrorMessageIsVisible: boolean;

    errorsSub:Subscription ;

    constructor(private customErrorHandler: CustomErrorHandler) {
    }

    ngOnInit()
    {
        this.errorsSub = this.customErrorHandler.errors.subscribe(
          (error) => {
                         this.showErrorMessage(error.message);   
                     });
    }

    showErrorMessage(msg: string)
    {
        this.ErrorMsg = msg;
        this.ErrorMessageIsVisible = true;
    }

    hideErrorMsg()
    {
        this.ErrorMessageIsVisible = false;
    }
}
1

1 Answers

0
votes

I think the issue is that you're not using the same instance of CustomErrorProvider.

Your provider is ErrorHandler:

@NgModule({
  providers: [{provide: ErrorHandler, useClass: CustomErrorHandler}]
})

In your Dialog you must inject ErrorHandler and cast to a CustomErrorHandler:

constructor(errorHandler: ErrorHandler) {
     this.customErrorHandler = errorHandler as CustomErrorHandler;
     ...
}