1

I have two separate queries using @tanstack/angular-query:

roles = injectQuery(() => ({
  enabled: this.user.data(),
  queryKey: ['roles'],
  queryFn: () =>
    lastValueFrom(getRoles({ roles: this.user.data().roles })),
}));

user = injectQuery(() => ({
  queryKey: ['user'],
  queryFn: () => lastValueFrom(getUser()),
}));

I want to keep these queries separate, but in the UI I want to consume them as one combined object, e.g.:

<div *ngIf="user.data() as user">
  roles: {{ user.roles.length }}
</div>

Ideally something like:

userActive = injectQueries(() => ({
  queries: [this.user, this.roles],
  select: (user, roles) => this.toUser(user, roles),
}));

toUser(user, roles) {
  return { ...user, roles: roles };
}

But I can't figure out how to combine the results like this. I also tried a computed signal, but computed() returns null until both queries load, and I'd prefer to stay within the TanStack Query API:

activeUser = computed(() => {
  const user = this.user.data();
  const roles = this.roles.data();
  if (!user) return;
  if (!roles) return;

  return this.toUser(user, roles);
});

Is there a built-in way in TanStack Query for Angular to derive/merge the results of two queries into one object (similar to injectQueries + select), while still keeping both queries independent?

1 Answer 1

-4
const userActive = injectQueries(() => ({
  queries: [this.user, this.roles],
  select: (user, roles) => {
    if (!user || !roles) return null;
    return {
      ...user,
      roles
    };
  }
}));

New contributor
Tarun Pal is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Sign up to request clarification or add additional context in comments.

2 Comments

it's not valid code.
injectQueries is under development for Angular Query, so this won’t work in the latest version as of writing (5.90.13).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.