1

I am trying to handle errors in angular. Not sure where exactly it should be handled, but I tried to do it in service.

@Injectable({
  providedIn: 'root',
})
export class CaseListService {
  public constructor(private httpClient: HttpClient, private router: Router) {}

  private get baseUrl() {
    return environment.apiBaseUrl || '/api';
  }

  public getCaseList(): Observable<CaseListModel[]> {
    return this.httpClient.get(this.baseUrl + '/cases').pipe(
      map((response) => response as Array<CaseListModel>),
      catchError((err: any) => {
        if (err.status) {
          console.log('Service temporarily unavailable' + err.status);
          this.router.navigate(['/unavailable']);
        }
        return throwError(err.statusText);
      })
    );
  }
}

And here is my component.ts where I am calling the service:

@Component({
  selector: 'app-case-list',
  templateUrl: './case-list.component.html',
  styleUrls: ['./case-list.component.css'],
})
export class CaseListComponent implements OnInit {
  title = 'List of cases';
  readonly CaseList$: Observable<CaseListModel[]>;

  constructor(private caseListService: CaseListService) {
    this.CaseList$ = caseListService.getCaseList();
  }

  displayedColumns: string[] = ['ID', 'name', 'actions'];
  dataSource = this.caseListService.getCaseList();

  ngOnInit(): void {}
}

I disabled backend and tried it. Result is just frontend with empty data. Redirect fails, console log shows nothing too. What am I doing wrong?

1 Answer 1

2

Check the angular documentation on http client error handling.

As you can see the status field of HttpErrorResponse is optional, meaning it could be undefined. This will explain why the console.log and navigate are not invoked.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah removing if really helps thanks morty.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.