1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Is there a way to dynamically compute rxResource() or resouce() in Angular (19)

Discussão em 'Angular' iniciado por Peter T., Maio 20, 2025.

  1. Peter T.

    Peter T. Guest

    Our use case: In a component we compute queries for data that should be fetched based on some config. I tried creating rxResource() within a compute to get the data - but also loading status and errors for each query individually.

    private readonly dataQueries = computed<DataQuery[]>(() => {
    // compute queries from component state
    });

    private readonly dataResources = linkedSignal<
    DataQuery[],
    DataResource[]
    >({
    source: this.dataQueries,
    computation: (newQueries, previousResult) => {
    // iterate over all queries and
    // check if we have a resource already for a query,
    // if yes, reuse the rxResource for it,
    // otherwise create a new one
    }
    }).asReadonly();

    protected readonly dataResults = computed<DataResults[]>(() =>
    this.dataResources().map((r) => r.value())
    );

    protected readonly dataStatuses = computed<ResourceStatus[]>(() =>
    this.dataResources().map((r) => r.status())
    );


    However, this approach has two main drawbacks:

    1. most important: rxResource uses internally effect() when constructed, and this is not allowed during computation of a signal value. (And for a good reason, I agree, as in most cases this is not what you want.)
    2. it does not appear as good style to me to use a linkedSignal to cache previous results in order to avoid re-creating resources for queries that existed already. (ngxtensions's extendedCompute is deprecated now and suggests to use a linkedSignal instead.)

    I could use a single rxResouce that holds the combined results - but I then loose the individual status and error state information.

    The classical approach would be to use Observables, I guess, and add loading state and errors to the results before assembling them into the final array. But as the resource() is a very nice way to combine value, state, and errors, it would be nice, if I could use this for each query.

    Do I miss something? Any suggestion?

    Continue reading...

Compartilhe esta Página