angularerror-handlingangular-errorhandler

errorHandle angular 7


How to manage error block in this situation - error managing in service and send to component

Here storing data in BehaviorSubject in the first load and subscribing data from where I need.

just initializing preload function from app.component when the app runs - but I want to know here if its an error

//**app component**
//just initializing preload function() when the app runs - but I want to know here if its an error
ngOnInit() {
    this.projectsService.preloadAllProjects();
}




// == services ==

//preload all projects
  preloadAllProjects(){
    this.http.get('/api/project/allprojects').pipe( map( response => response )).subscribe(result => {
      this.allProjectsBehavior.next(result);
    });
  };

Solution

  • If you want to follow the subject path:

    //**app component**
    //just initializing preload function() when the app runs - but I want to know here if its an error
    ngOnInit() {
        this.projectsService.preloadAllProjects();
        this.projectService.error$.subscribe(error => console.log(error));
    }
    
    
    
    
    // == services ==
    
    //preload all projects
      error$: Subject<string> = new Subject();
      preloadAllProjects(){
        this.http.get('/api/project/allprojects').pipe( map( response => response )).subscribe(result => {
          this.allProjectsBehavior.next(result);
        }, error => this.error$.next(error);
      };
    

    or you can basically return an Observable from preloadAllProjects:

    //**app component**
    //just initializing preload function() when the app runs - but I want to know here if its an error
    ngOnInit() {
        this.projectsService.preloadAllProjects().subscribe(success => {}, error => console.log(error))
    }
    
    
    
    
    // == services ==
    
    //preload all projects
      error$: Subject<string> = new Subject();
      preloadAllProjects(){
        return new Observable(observer => {
        this.http.get('/api/project/allprojects').pipe( map( response => response )).subscribe(result => {
          this.allProjectsBehavior.next(result);
          observer.next(true);
          observer.complete();
        }, error => observer.error(error);
       });
      };