在创建rxResource时,应该避免初始请求吗?

前端开发 2026-07-12

在使用 rxResource 构建Angular的 RxJS互操作时,创建时会对我的HTTP资源进行一次初始请求。有什么办法可以阻止吗?

解决方案

是的,我们只需要在 params 上返回 undefined(大于Angular 19的版本)或在 request 上返回 undefined(等于或小于Angular 19的版本)。只有在正确设置所需的 signals 之后,才会触发API调用。


修复:返回 undefined,以防在就绪前触发API。

TS:

export class AppComponent {
  httpClient = inject(HttpClient);
  id = signal<any>({ id: undefined });
  resourceFetchedAlways = rxResource({
    // if using angular 19 less or equal versions
    // replace params, with request and stream with loader.
    // you can just do this.id()?.id for simplicity
    params: () => {
      const idData = this.id();
      // here api is not called unless id value is present
      if(idData?.id) {
        return idData;
      }
      // return undefined to prevent API call trigger
      return undefined;
    },
    stream: ({ params: { id } }) => {
      return this.httpClient.get(
        `https://jsonplaceholder.typicode.com/todos/${id}`
      );
    },
  });

  ngOnInit() {
    setTimeout(() => {
      this.id.set({ id: 2 });
    }, 3000);
  }
}

HTML:

<p>Angular 21 Works!</p>
@let status = resourceFetchedAlways.status(); 
@if(status === 'idle') { 
  Resource API is idle 
} @if(status === 'error') { 
  Error! 
} @if(status === 'resolved') {
  {{ resourceFetchedAlways.value() | json }}
}

Stackblitz演示


问题演示:如果不返回 undefined,在初始化时API将始终被触发(错误)。
export class AppComponent {
  httpClient = inject(HttpClient);
  id = signal({ id: undefined });
  resourceFetchedAlways = rxResource({
    params: () => this.id(),
    stream: ({ params: { id } }) => {
      return this.httpClient.get(
        `https://jsonplaceholder.typicode.com/todos/${id}`
      );
    },
  });
}

Stackblitz演示

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章