【问题标题】:Handling errors in angular service处理角度服务中的错误
【发布时间】:2021-07-17 11:07:13
【问题描述】:

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

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

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

【问题讨论】:

    标签: angular typescript error-handling


    【解决方案1】:

    在 http 客户端错误处理上检查 angular documentation

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

    【讨论】:

    • 是的,如果真的有帮助,请删除谢谢莫蒂。
    猜你喜欢
    • 2018-04-08
    • 2018-01-29
    • 2019-01-11
    • 2019-11-14
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    相关资源
    最近更新 更多