处理 angular 服务中的错误

Handling errors in angular service

我正在尝试处理 angular 中的错误。不确定应该在哪里处理,但我尝试在服务中进行处理。

@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);
      })
    );
  }
}

这里是我的 component.ts 我调用服务的地方:

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

我禁用了后端并试过了。结果只是带有空数据的前端。重定向失败,控制台日志也没有显示任何内容。我做错了什么?

检查有关 http 客户端错误处理的 angular documentation

如您所见,HttpErrorResponse 的状态字段是可选的,这意味着它可以是未定义的。这将解释为什么 console.lognavigate 没有被调用。