1

I have a service that gets a json from http

I created a dialog for errors in my main app, but I dont understand how you give back the potential error to the applicationi so it displays it on the web page

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 ?
                },
            );
    }
}

thanks

1
  • can you paste the code of your component also? Commented Feb 24, 2017 at 9:57

1 Answer 1

1

I would implement a custom global error handler:

 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 {}

Then in your error dialog component:

class ErrorDialog implements OnInit {
    constructor(private errorHandler: MyErrorHandler) {

    }

    ngOnInit() {
       this.errorHandler.errorEvent$.subscribe(t=> {
            // show dialog here
       });
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

neat,.... btw I dont understand why it's called an observer since its the one that will provide data to the stream, not the part that will subscribe and "listen" to the observable
what is the @ before private ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.