You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 19中如何获取Resource的错误信息

Angular 19中如何获取Resource的错误信息

嘿,我看到你在Angular 19里用了新的rxResource来加载数据,想知道怎么捕获它的错误信息对吧?这就给你分享两种实用的处理方式~

首先先贴一下你的原始代码,方便对照:

// Skipping imports and decorators for simplicity
export class ApiService {
  http = inject(HttpClient);

  public myResource = rxResource<MyThing[], void>({
    loader: () => this.getMyThing(),
    defaultValue: [],
  })

  private getMyThing(): Observable<MyThing[]> {
    return this.http.get<MyThing[]>(`${environment.apiBaseUrl}/mything/`);
  }
}

方法一:在rxResource配置中添加错误处理器

你可以直接在rxResource的配置对象里加入errorHandler属性,用来处理加载过程中出现的错误。这里可以做错误日志记录、给用户提示,甚至返回一个 fallback 值:

public myResource = rxResource<MyThing[], void>({
  loader: () => this.getMyThing(),
  defaultValue: [],
  errorHandler: (error) => {
    // 打印错误详情到控制台
    console.error('资源加载失败:', error);
    // 这里可以添加用户友好的提示,比如调用通知组件
    // this.notificationService.showError('数据加载失败,请稍后重试');
    
    // 如果需要的话,你也可以重新抛出错误,让上层订阅者处理
    // throw error;
  }
})

方法二:订阅resource的error$流

rxResource实例自带了error$这个Observable,你可以在组件或者其他服务里订阅它,在需要的地方处理错误:

比如在你的组件中:

import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html'
})
export class MyComponent implements OnInit {
  constructor(private apiService: ApiService) {}

  ngOnInit(): void {
    // 订阅错误流
    this.apiService.myResource.error$.subscribe(error => {
      console.error('捕获到资源错误:', error);
      // 这里可以更新UI状态,比如显示错误提示框
    });
  }
}

另外补充一下,rxResource还提供了loading$(加载状态)和data$(数据)这两个Observable,你可以一起订阅来构建完整的加载状态逻辑哦~

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 13:04:33