我正在尝试处理角度错误。不确定应该在哪里处理,但我尝试在服务中进行。
@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 {}
}
我禁用了后端并尝试了它。结果只是带有空数据的前端。重定向失败,控制台日志也没有显示任何内容。我做错了什么?
答案 0 :(得分:1)
检查 http 客户端错误处理的角度 documentation。
如您所见,HttpErrorResponse 的状态字段是可选的,这意味着它可以是未定义的。这将解释为什么不调用 console.log
和 navigate
。