@molecule/app-query-angular

Feature · query · App (browser) · v1.5.0 · Apache-2.0

Angular hooks for @molecule/app-query — read a cached document synchronously, observe it, and prefetch on intent

npm install @molecule/app-query-angular

npm · Source on GitHub

How it works

@molecule/app-query-angular is a ready-made query feature for the app (browser) side. It composes the core interfaces it needs, so it works with whichever providers your app has bonded.

import { Component, OnChanges, computed, input } from '@angular/core'
import { useTranslation } from '@molecule/app-angular'
import { getClient, isHttpError } from '@molecule/app-http'
import { intentPrefetchProps, useQuery } from '@molecule/app-query-angular'

interface PackageDocument {
  name: string
  description: string
}

const packageQuery = (name: string) => ({
  key: ['package', name],
  fetch: async (signal: AbortSignal): Promise<PackageDocument | null> => {
    try {
      const response = await getClient().get<PackageDocument | null>(
        `/data/packages/${encodeURIComponent(name)}.json`,
        { signal },
      )
      return response.data
    } catch (error) {
      if (isHttpError(error) && error.status === 404) return null
      throw error
    }
  },
})

// A link warms its document at the first sign of intent: the handlers
// `intentPrefetchProps` returns are named after the DOM events an Angular
// template binds, so a component puts them on its host listeners.
@Component({
  selector: 'a[mol-package-link]',
  template: '<ng-content></ng-content>',
  inputs: ['name'],
  host: {
    '(pointerenter)': 'warm.pointerenter()',
    '(focus)': 'warm.focus()',
    '(touchstart)': 'warm.touchstart()',
  },
})
export class PackageLink implements OnChanges {
  name = ''

  warm = intentPrefetchProps(packageQuery(this.name))

  ngOnChanges(): void {
    this.warm = intentPrefetchProps(packageQuery(this.name))
  }
}

// The page reads the document synchronously when it is cached (a warmed page
// opens with no loading state) and follows a changed name on the same
// instance. Until a name arrives, `null` observes nothing.
@Component({
  selector: 'mol-package-page',
  template: `
    @if (query.status === 'error') {
      <p role="alert">
        {{ t('packages.loadFailed', undefined, { defaultValue: 'Unable to load package.' }) }}
      </p>
    } @else if (query.status === 'idle' || query.status === 'loading') {
      <p role="status">{{ t('common.loading', undefined, { defaultValue: 'Loading…' }) }}</p>
    } @else if (query.data === null) {
      <p>{{ t('packages.notFound', undefined, { defaultValue: 'Package not found.' }) }}</p>
    } @else {
      <article>
        <h1>{{ query.data?.name }}</h1>
        <p>{{ query.data?.description }}</p>
      </article>
    }
  `,
})
export class PackagePage {
  // The binding's t re-runs the template on a locale switch.
  protected readonly t = useTranslation().t
  readonly name = input('')

  readonly query = useQuery<PackageDocument | null>(
    computed(() => (this.name() ? packageQuery(this.name()) : null)),
  )
}

// `<a [mol-package-link][name]="next" [href]="href">{{ next }}</a>` warms the
// next package while the reader hovers, focuses or touches the link, so the
// page it opens renders from cache with no loading state.

Works with: @molecule/app-angular, @molecule/app-query

Reference

Angular hooks for @molecule/app-query — the Angular counterpart of @molecule/app-query-react, with the same exports, the same contracts and the same rendered result for the same input.

Load page data with useQuery, not a hand-written load effect. An effect that cancels its own request on cleanup (a cancelled flag, or an AbortController) re-runs its cleanup whenever one of its tracked dependencies is a function created inline each run — and its own guard then returns without refetching, so the response is discarded whenever it arrives after a re-render: always on a remote server, never on localhost, which is why the page passes locally and fails on the live URL. useQuery subscribes once per key, keeps its request stable across template refreshes, and aborts it only when the key changes or the component is destroyed.

useQuery observes one document from the app's shared cache and returns cached data on the first read; usePrefetch and intentPrefetchProps warm a document when a person is about to open it. Together they make a detail page open with no loading state.

This package needs a bonded client: install @molecule/app-query with a bond (@molecule/app-query-memory, or @molecule/app-query-tanstack) and call the bond's setProvider(provider) once at startup (the scaffold's app/src/bonds/ does this). Call the hooks in an injection context — a component field initializer or constructor. A component whose options change with its own state passes a Signal of options (an input()/computed()), and every change is followed on the same instance, the way React re-renders useQuery with a new options object.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { Component, OnChanges, computed, input } from '@angular/core'
import { useTranslation } from '@molecule/app-angular'
import { getClient, isHttpError } from '@molecule/app-http'
import { intentPrefetchProps, useQuery } from '@molecule/app-query-angular'

interface PackageDocument {
  name: string
  description: string
}

const packageQuery = (name: string) => ({
  key: ['package', name],
  fetch: async (signal: AbortSignal): Promise<PackageDocument | null> => {
    try {
      const response = await getClient().get<PackageDocument | null>(
        `/data/packages/${encodeURIComponent(name)}.json`,
        { signal },
      )
      return response.data
    } catch (error) {
      if (isHttpError(error) && error.status === 404) return null
      throw error
    }
  },
})

// A link warms its document at the first sign of intent: the handlers
// `intentPrefetchProps` returns are named after the DOM events an Angular
// template binds, so a component puts them on its host listeners.
@Component({
  selector: 'a[mol-package-link]',
  template: '<ng-content></ng-content>',
  inputs: ['name'],
  host: {
    '(pointerenter)': 'warm.pointerenter()',
    '(focus)': 'warm.focus()',
    '(touchstart)': 'warm.touchstart()',
  },
})
export class PackageLink implements OnChanges {
  name = ''

  warm = intentPrefetchProps(packageQuery(this.name))

  ngOnChanges(): void {
    this.warm = intentPrefetchProps(packageQuery(this.name))
  }
}

// The page reads the document synchronously when it is cached (a warmed page
// opens with no loading state) and follows a changed name on the same
// instance. Until a name arrives, `null` observes nothing.
@Component({
  selector: 'mol-package-page',
  template: `
    @if (query.status === 'error') {
      <p role="alert">
        {{ t('packages.loadFailed', undefined, { defaultValue: 'Unable to load package.' }) }}
      </p>
    } @else if (query.status === 'idle' || query.status === 'loading') {
      <p role="status">{{ t('common.loading', undefined, { defaultValue: 'Loading…' }) }}</p>
    } @else if (query.data === null) {
      <p>{{ t('packages.notFound', undefined, { defaultValue: 'Package not found.' }) }}</p>
    } @else {
      <article>
        <h1>{{ query.data?.name }}</h1>
        <p>{{ query.data?.description }}</p>
      </article>
    }
  `,
})
export class PackagePage {
  // The binding's t re-runs the template on a locale switch.
  protected readonly t = useTranslation().t
  readonly name = input('')

  readonly query = useQuery<PackageDocument | null>(
    computed(() => (this.name() ? packageQuery(this.name()) : null)),
  )
}

// `<a [mol-package-link][name]="next" [href]="href">{{ next }}</a>` warms the
// next package while the reader hovers, focuses or touches the link, so the
// page it opens renders from cache with no loading state.

A list whose page and filter live in the URL: derive the key from the route (a computed over the route inputs) and pass keepPreviousData with a principal, so a page/filter change keeps the rows already on screen until the next page answers. The app's HTTP client sends the session, so the viewer is part of what the answer depends on: key on it and pass the same value as principal — an account switch then drops the previous account's rows at once. Pass null while the session is still being restored (status === 'loading'; the HTTP client holds the request until then anyway), so restoring a session never swaps a key that already rendered rows.

import { Component, computed, input } from '@angular/core'
import { useTranslation } from '@molecule/app-angular'
import { getClient, unwrapList } from '@molecule/app-http'
import { useQuery } from '@molecule/app-query-angular'

interface Invoice {
  id: string
  number: string
}

@Component({
  selector: 'mol-invoice-list',
  template: `
    @if (query.status === 'loading' || query.isFetching) {
      <p role="status">{{ t('common.loading', undefined, { defaultValue: 'Loading…' }) }}</p>
    }
    @if (query.status === 'error') {
      <p role="alert">
        {{ t('invoices.loadFailed', undefined, { defaultValue: 'Unable to load invoices.' }) }}
      </p>
    }
    <ul>
      @for (invoice of query.data ?? []; track invoice.id) {
        <li>
          <a [href]="'/invoices/' + invoice.id">{{ invoice.number }}</a>
        </li>
      }
    </ul>
    @if (!query.isPreviousData && query.data?.length === 0) {
      <p>{{ t('invoices.empty', undefined, { defaultValue: 'No invoices yet.' }) }}</p>
    }
    <a [href]="nextHref()">{{ t('common.next', undefined, { defaultValue: 'Next page' }) }}</a>
  `,
})
export class InvoiceList {
  // The binding's t re-runs the template on a locale switch.
  protected readonly t = useTranslation().t
  // The viewer whose invoices these are (also in the key).
  readonly viewer = input('anonymous')
  // The page to show.
  readonly page = input(1)

  readonly query = useQuery<Invoice[]>(
    computed(() => ({
      key: ['invoices', this.viewer(), this.page()],
      principal: this.viewer(),
      keepPreviousData: true,
      fetch: async (signal: AbortSignal) =>
        unwrapList<Invoice>(
          await getClient().get('/api/invoices', {
            signal,
            params: { limit: 20, offset: (this.page() - 1) * 20 },
          }),
        ),
    })),
  )

  readonly nextHref = computed(() => `/invoices?page=${this.page() + 1}`)
}

A mutation or a failed load has to change a page that is ALREADY mounted, and the cache never starts that request by itself: set() paints a mutation's own response, invalidate() marks what it affects for the next mount, and an explicit fetch() retries into the mounted page.

import { Component, input } from '@angular/core'
import { useTranslation } from '@molecule/app-angular'
import { getClient } from '@molecule/app-http'
import { getQueryClient } from '@molecule/app-query'

// The key names what the document actually depends on — here the signed-in
// principal, the filter and the page. Another principal's feed is a
// different document, so an invalidation scoped to this one leaves it alone.
const feedKey = (principal: string, filter: string, page: number) =>
  ['feed', principal, filter, page] as const

const feedOptions = (principal: string, filter: string, page: number) => ({
  key: feedKey(principal, filter, page),
  fetch: async (signal: AbortSignal) =>
    (await getClient().get(`/api/feeds/${filter}`, { signal, params: { page } })).data,
})

async function setFollowing(principal: string, authorId: string, follow: boolean): Promise<void> {
  const client = getQueryClient()
  const http = getClient()
  const { data: body } = follow
    ? await http.post<{ feed: unknown }>(`/api/follows/${authorId}`)
    : await http.delete<{ feed: unknown }>(`/api/follows/${authorId}`)
  // The response IS the document: paint it now, with no second round trip.
  // (If it were only a count or a flag, skip set() and invalidate() instead.)
  client.set(feedKey(principal, 'following', 1), body.feed)
  // Future reads of every feed this principal owns are stale.
  client.invalidate(['feed', principal])
}

@Component({
  selector: 'button[mol-feed-retry]',
  template: `{{ t('common.retry', undefined, { defaultValue: 'Retry' }) }}`,
  host: { type: 'button', '(click)': 'retry()' },
})
export class FeedRetry {
  // The binding's t re-runs the template on a locale switch.
  protected readonly t = useTranslation().t
  readonly principal = input.required<string>()

  retry(): void {
    // invalidate() alone would leave the mounted page on its error;
    // an explicit fetch retries into it. useQuery shows the outcome.
    void getQueryClient()
      .fetch(feedOptions(this.principal(), 'following', 1))
      .catch((_error) => {
        // The mounted useQuery observer presents this failure via status/error.
      })
  }
}

One API resource described once, for every page that reads or changes it. createQueryResource returns the list and detail reads as useQuery options and the writes as functions that put the server's record into the cache and fetch the lists on screen again, so a page never mirrors a response into component state. A flag the API models as a sub-path (POST /invoices/:id/flag, DELETE to clear it) is toggle, which resolves with the saved record and is the commit of OptimisticToggleButton (from @molecule/app-ui-angular).

import { Component, computed, input } from '@angular/core'
import { useTranslation } from '@molecule/app-angular'
import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
import { OptimisticToggleButton } from '@molecule/app-ui-angular'
import { createQueryResource, QueryContent, useQuery } from '@molecule/app-query-angular'

interface Invoice {
  id: string
  number: string
  flagged: boolean
}

export const invoices = createQueryResource<Invoice>({
  name: 'invoices',
  path: '/invoices',
  http: getClient,
  readList: (response) => unwrapList<Invoice>(response),
  readOne: (response) => unwrapSingle<Invoice | null>(response),
})

// The record's own action: a flag control whose click shows at once, whose
// save follows, and whose label goes back to the server's value only when the
// save fails. OptimisticToggleButton takes the server value as an input, so a
// fresh query answer updates it after a completed save.
@Component({
  selector: 'mol-flag-control',
  template: `
    <button type="button" mol-optimistic-toggle-button [value]="invoice().flagged" [commit]="save">
      <span slot="activeLabel">{{
        t('invoice.unflag', undefined, { defaultValue: 'Unflag' })
      }}</span>
      <span slot="inactiveLabel">{{ t('invoice.flag', undefined, { defaultValue: 'Flag' }) }}</span>
      {{ invoice().number }}
    </button>
  `,
  imports: [OptimisticToggleButton],
})
export class InvoiceFlagControl {
  readonly invoice = input.required<Invoice>()
  readonly viewer = input.required<string>()
  // The binding's t re-runs the template on a locale switch.
  protected readonly t = useTranslation().t

  readonly save = async (flagged: boolean): Promise<boolean> =>
    (await invoices.toggle(this.viewer(), this.invoice().id, 'flag', flagged)).flagged
}

// Render the record's own container (here the flag control) through
// QueryContent: its children template runs only with a loaded, non-null
// document, so an action can never swallow an early click. Every status
// line stays beside it.
@Component({
  selector: 'mol-invoice-page',
  template: `
    <mol-query-content
      [query]="query"
      [pending]="pending"
      [missing]="missing"
      [error]="failed"
      [children]="content"
    >
      <ng-template #pending>
        <p role="status">{{ t('common.loading', undefined, { defaultValue: 'Loading…' }) }}</p>
      </ng-template>
      <ng-template #missing>
        <p role="alert">
          {{ t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' }) }}
        </p>
      </ng-template>
      <ng-template #failed let-_error>
        <p role="alert">
          {{ t('invoice.failed', undefined, { defaultValue: 'Unable to load invoice.' }) }}
        </p>
      </ng-template>
      <ng-template #content let-invoice>
        <mol-flag-control [invoice]="invoice" [viewer]="viewer()"></mol-flag-control>
      </ng-template>
    </mol-query-content>
  `,
  imports: [QueryContent, InvoiceFlagControl],
})
export class InvoicePage {
  // The binding's t re-runs the template on a locale switch.
  protected readonly t = useTranslation().t
  readonly id = input('')
  readonly viewer = input('')

  readonly query = useQuery(
    computed(() => (this.viewer() && this.id() ? invoices.detail(this.viewer(), this.id()) : null)),
  )
}

A pager needs the whole response, including its total. Keep that read on the same resource as its mutations, including alternate list paths; a separate hand-written options object is outside the resource's refresh tracking.

import { getClient } from '@molecule/app-http'
import { createQueryResource } from '@molecule/app-query-angular'

interface TicketPage {
  tickets: { id: string; subject: string }[]
  total: number
}
const tickets = createQueryResource<TicketPage['tickets'][number]>({
  name: 'tickets',
  path: '/tickets',
  http: getClient,
  readOne: (response) => response.data as TicketPage['tickets'][number],
})
const page = tickets.listPage(
  'agent-1',
  { limit: 10, offset: 20 },
  (response) => response.data as TicketPage,
)
// useQuery(page) observes both rows and total. tickets.create/update/remove/toggle
// and tickets.refresh('agent-1') refresh this page too.
// A second list can use tickets.listPage(viewer, params, readPage, '/tickets/open').
// Use one canonical page reader per path; list() still returns only its own rows.
// For immediate deletion from an opaque page, add a fifth argument:
// (page, id) => {
//   const rows = page.tickets.filter((row) => String(row.id) !== id)
//   return { ...page, tickets: rows, total: page.total - (page.tickets.length - rows.length) }
// }

A resource mutation also waits out a pre-mutation list request before fetching again; joining that older in-flight read alone would leave the new record absent. Successful deletion removes a row immediately, including one just created through the resource. Stale reads cannot restore acknowledged deletions for that viewer; an explicit successful create can recreate the identity. Opaque listPage envelopes need their own removeFromPage adapter; no row or total property is guessed.

Type

feature

Installation

npm install @molecule/app-query-angular @angular/common @angular/core @angular/platform-browser @molecule/app-angular @molecule/app-query

API

Interfaces

ResourceResponse

The part of an HTTP response a resource reads.

interface ResourceResponse {
  /** The parsed response body. */
  data: unknown
}

ResourceHttp

The HTTP client a resource calls: the app's own bonded client (getClient() from @molecule/app-http) has this shape. Only what a resource uses is named here.

interface ResourceHttp {
  /** Reads `path`; `signal` cancels it and `params` become the query string. */
  get(
    path: string,
    options?: { signal?: AbortSignal; params?: Record<string, unknown> },
  ): Promise<ResourceResponse>
  /** Creates at `path`. */
  post(path: string, body?: unknown): Promise<ResourceResponse>
  /** Replaces at `path`. */
  put(path: string, body?: unknown): Promise<ResourceResponse>
  /** Changes part of the record at `path`. */
  patch(path: string, body?: unknown): Promise<ResourceResponse>
  /** Removes at `path`. */
  delete(path: string): Promise<ResourceResponse>
}

QueryResourceConfig

What createQueryResource needs to know about one resource.

interface QueryResourceConfig<T> {
  /** The first element of every cache key of this resource, e.g. `'invoices'`. */
  name: string
  /** The collection's path under the API base, e.g. `'/invoices'`. */
  path: string
  /** The app's HTTP client, read on every call so a client bonded later is the one used. */
  http: () => ResourceHttp
  /** The field a record is addressed by in a URL. Defaults to `'id'`. */
  id?: keyof T & string
  /** The HTTP method the API updates a record with. Defaults to `'put'`. */
  updateMethod?: 'put' | 'patch'
  /** Reads the records out of a list response. Defaults to the body itself. */
  readList?: (response: ResourceResponse) => T[]
  /** Reads the record out of a detail or write response. Defaults to the body itself. */
  readOne?: (response: ResourceResponse) => T | null
}

QueryResource

The reads and writes createQueryResource returns.

interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
  /**
   * `useQuery` options for the collection. `viewer` is who the answer is for (the signed-in id,
   * or `'anonymous'`); a page or filter change keeps the rows on screen until the next answer.
   * One record per URL identity, retaining the first occurrence. Equal values without an
   * addressable id remain separate. Writes already refresh the collection.
   */
  list(viewer: string, params?: Record<string, unknown>): QueryOptions<T[]>
  /**
   * Options for a collection's whole page (rows plus totals), or a filtered collection path.
   * Reads share this resource's mutation refresh and viewer isolation. `readPage` reads the
   * canonical page response for `path`; row-only `list` reads keep a separate cache entry.
   * Supply `removeFromPage` for opaque page envelopes to remove acknowledged deletions
   * immediately and keep stale list responses from restoring them.
   */
  listPage<Page>(
    viewer: string,
    params: Record<string, unknown>,
    readPage: (response: ResourceResponse) => Page,
    path?: string,
    removeFromPage?: (page: Page, id: string) => Page,
  ): QueryOptions<Page>
  /**
   * `useQuery` options for one record, or null while `id` is not known yet (`useQuery(null)`
   * observes nothing). An empty ID is also unknown. A missing record resolves to null.
   */
  detail(viewer: string, id: string | null | undefined): QueryOptions<T | null> | null
  /** Creates a record, shows it in the cache and refreshes the lists on screen. */
  create(viewer: string, input: Create): Promise<T>
  /** Updates a record, shows the saved record in the cache and refreshes the lists on screen. */
  update(viewer: string, id: string, input: Update): Promise<T>
  /** Removes a record from detail and tracked row lists, then refreshes those lists. */
  remove(viewer: string, id: string): Promise<void>
  /**
   * Switches a flag the API models as a sub-path: `POST path/id/action` turns it on and
   * `DELETE path/id/action` turns it off. Resolves with the saved record, so it is the `commit`
   * of `useOptimisticValue`. Rejects an absent or empty record ID before sending a request.
   * The saved detail is published before tracked lists finish refreshing; this promise waits
   * for those refreshes. Render the shared controller's value and let it queue inverse clicks
   * during that interval. A page-local busy guard can drop a click on the newly changed label.
   */
  toggle(viewer: string, id: string, action: string, on: boolean): Promise<T>
  /** Fetches the lists on screen again, after a change this resource did not make itself. */
  refresh(viewer: string): Promise<void>
}

ListQueryRoute

The list route a list query reads: useListRoute from @molecule/app-angular returns these signals (and more), so its result is passed as it is.

interface ListQueryRoute<Filter extends string = string> {
  /** False while a protected view waits for auth, is signed out, or is unavailable. */
  readonly canLoad: Signal<boolean>
  /** The current URL filter values. */
  readonly filters: Signal<Readonly<Record<Filter, string | undefined>>>
  /** The configured items per page. */
  readonly pageSize: Signal<number>
  /** The zero-indexed item offset for the API request. */
  readonly offset: Signal<number>
}

ListQueryState

The route's current values, as read receives them.

interface ListQueryState<Filter extends string = string> {
  /** The current URL filter values. */
  readonly filters: Readonly<Record<Filter, string | undefined>>
  /** The configured items per page. */
  readonly pageSize: number
  /** The zero-indexed item offset for the API request. */
  readonly offset: number
}

UseQueryResult

A mounted query's state and its explicit cache and refresh actions. The state fields read as plain values at read time (each reads the observer's current state signal), so a template binding that calls them re-renders when the document changes, and a test can snapshot the object at any moment.

interface UseQueryResult<T> extends QueryState<T> {
  /**
   * Publish a saved document to this key and all its observers. Render `data`
   * directly instead of copying it to local state: later cache updates then
   * remain visible. A function receives this key's current cached document,
   * never retained previous-page data. Returning `undefined` leaves the cache
   * unchanged. A disabled (`null`) query does nothing, including not calling an
   * updater. Like React state setters, wrap a function-valued document in an
   * updater. A saved callback stays bound to its original key. The write
   * supersedes older in-flight reads, using the bonded client's `set` contract.
   */
  setData: (value: T | ((previous: T | undefined) => T | undefined)) => void
  /**
   * Fetch this key again, even when its cached document is fresh. Observers
   * receive the updated state. Resolves with that state, including an error
   * when the request fails; a disabled (`null`) query resolves idle without a
   * request.
   */
  refetch: () => Promise<QueryState<T>>
}

QueryContentContext

The context a children template receives: the loaded, non-null document, as $implicit and as the render function's first argument (a0).

interface QueryContentContext<T> {
  /** The loaded document (never `undefined` or `null`). */
  $implicit: NonNullable<T>
  /** The same document, as the first render argument. */
  a0: NonNullable<T>
}

QueryContentErrorContext

The context an error template receives: the failed read's error value, as $implicit and as the render function's first argument (a0).

interface QueryContentErrorContext {
  /** The error the failed read rejected with. */
  $implicit: Error
  /** The same error, as the first render argument. */
  a0: Error
}

QueryContentProps

A loaded document owns its controls; absent documents expose only status content.

interface QueryContentProps<T> {
  /**
   * One optional empty branch, exclusive with children. The pure predicate reads the
   * loaded document (an array or an application-owned envelope); render selects the
   * current view's message and recovery action. A previous key's empty document uses
   * pending/error instead. Omit it to keep empty arrays as data.
   */
  empty?: {
    when: (data: NonNullable<T>) => boolean
    render: NonNullable<QueryContentProps<T>['children']>
  }

  /** State from useQuery, or any compatible query observer. */
  query: Pick<QueryState<T>, 'data' | 'status' | 'error' | 'isPreviousData'>
  /**
   * Stable identity of the requested record, including the principal when needed.
   * Use for record-specific state such as an edit form. Changing the key remounts the
   * loaded branch and excludes data retained from a previous query key.
   */
  recordKey?: PropertyKey
  /** Mounted only with a real document, including false, zero and an empty list. */
  children: TemplateRef<QueryContentContext<T>> | null
  /** Initial idle/loading content. Render a status template, never a fake item or action. */
  pending?: TemplateRef<unknown> | null
  /** Content for a loaded null record. Null is distinct from an unfinished request. */
  missing?: TemplateRef<unknown> | null
  /** A failed initial read. Cached data stays visible if its refresh fails. */
  error?: TemplateRef<QueryContentErrorContext> | null
}

QueryRecordContentProps

A loaded document and its verified identity, required to render the record's actions.

interface QueryRecordContentProps<T, Id extends string | number> extends Omit<
  QueryContentProps<T>,
  'children'
> {
  /** Extracts the ID from the loaded document. Null, undefined and an empty string are pending. */
  getRecordId: (data: QueryContentContext<T>['$implicit']) => Id | null | undefined
  /** Receives the ID with the document. The branch remounts when the ID or recordKey changes. */
  children: TemplateRef<QueryRecordContentContext<T, NoInfer<Id>>> | null
}

IntentPrefetchProps

The handlers intentPrefetchProps returns, named after the DOM events an Angular template binds ((pointerenter), (focus), (touchstart)).

interface IntentPrefetchProps {
  /** Warms the document when the pointer arrives. */
  pointerenter: () => void
  /** Warms the document on keyboard focus. */
  focus: () => void
  /** Warms the document when a touch starts. */
  touchstart: () => void
}

Types

ListQuerySource

A plain value or a signal: each input useListQuery reads reactively.

type ListQuerySource<T> = T | Signal<T>

ListQueryInputs

Each input of useListQuery as a ListQuerySource.

type ListQueryInputs<Values> = {
  readonly [Key in keyof Values]: ListQuerySource<Values[Key]>
}

QueryOptionsInput

What useQuery observes: the options for one key or null (nothing), as plain values or a signal of them.

type QueryOptionsInput<T> =
  | (QueryOptions<T> & { enabled?: boolean })
  | null
  | Signal<(QueryOptions<T> & { enabled?: boolean }) | null>

QueryContentSlots

The content QueryContentProps renders for each state: the loaded-data branch, the pending and missing content and the error renderer (the templates the component takes as inputs).

type QueryContentSlots<T> = Pick<QueryContentProps<T>, 'children' | 'pending' | 'missing' | 'error'>

Classes

QueryContent

The loaded-data branch receives a non-null document. Pending, failed initial reads and missing records never mount that branch, so its actions cannot swallow an early click. Cached data remains mounted during refresh, including a failed refresh. Status fallbacks belong outside the list or record container rendered by children, and so does a refresh line; the default fallbacks render nothing. A previous key's empty or missing document renders pending/error until the current key answers. Pass recordKey for an edit form: the form mounts with the current record and resets when its identity changes, including a switch to a record already in cache. Pass getRecordId to bind actions to the loaded document's identity: the branch stays pending without a nonempty ID and receives the ID as template context a1 (let-id="a1").

The templates receive the render arguments as template context: children gets the document as $implicit and a0 (let-data), the record-bound branch also gets the ID as a1 (let-id), error gets the error value (let-error), and pending/missing render without a context.

@Component({
  selector: 'mol-query-content',
  standalone: true,
  hostDirectives: [MolPlacement],
  template: '<ng-container #outlet></ng-container>',
  inputs: ['query', 'pending', 'missing', 'children', 'error', 'empty', 'recordKey', 'getRecordId'],
})
export class QueryContent<T = unknown> implements DoCheck, OnChanges {
  /** State from useQuery, or any compatible query observer. */
  query: QueryContentProps<T>['query'] = { data: undefined, status: 'idle', error: undefined }
  /**
   * Stable identity of the requested record, including the principal when needed.
   * Use for record-specific state such as an edit form. Changing the key remounts the
   * loaded branch and excludes data retained from a previous query key.
   */
  recordKey: QueryContentProps<T>['recordKey'] = undefined
  /**
   * Extracts the ID from the loaded document. Null, undefined and an empty string
   * are pending. With it set, `children` receives the ID as template context `a1`.
   */
  getRecordId: QueryRecordContentProps<T, string | number>['getRecordId'] | undefined = undefined
  /** Mounted only with a real document, including false, zero and an empty list. */
  children:
    QueryContentProps<T>['children'] | QueryRecordContentProps<T, string | number>['children'] =
    null
  /** Initial idle/loading content. Render a status template, never a fake item or action. */
  pending: TemplateRef<unknown> | null = null
  /** Content for a loaded null record. Null is distinct from an unfinished request. */
  missing: TemplateRef<unknown> | null = null
  /** One empty collection template, exclusive with the loaded children. */
  empty: QueryContentProps<T>['empty'] = undefined
  /** A failed initial read. Cached data stays visible if its refresh fails. */
  error: TemplateRef<QueryContentErrorContext> | null = null

  /** Where the chosen branch renders. */
  @ViewChild('outlet', { read: ViewContainerRef, static: true })
  private outlet!: ViewContainerRef
  /** Marks this region for check when the observed document changes. */
  private readonly changeDetector = inject(ChangeDetectorRef)
  /** The observer the reactivity effect is subscribed to (a new prop re-subscribes it). */
  private readonly observer = signal<QueryContentProps<T>['query']>(this.query)
  /** The template currently mounted. */
  private current: TemplateRef<unknown> | null = null
  /** The record the mounted branch belongs to (`recordKey` when it last mounted). */
  private mountedRecord: PropertyKey | undefined = undefined
  /** The document identity the mounted branch belongs to, when `getRecordId` is set. */
  private mountedId: string | number | undefined = undefined
  /** The context object the mounted view reads (updated in place). */
  private readonly context: Record<string, unknown> = {}
  /** The mounted branch view, when a template is showing. */
  private view?: EmbeddedViewRef<unknown>

  /** The component's host element (React renders the branch and nothing of its own). */
  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  constructor() {
    // The branch renders in front of the host's place and the host leaves the page, so the
    // DOM is exactly the branch's own (React returns the branch element directly).
    usePlacement(() => {
      placeContentBefore(this.host.nativeElement, this.host.nativeElement)
      setElementPresent(this.host.nativeElement, false)
    })
    // A `useQuery` result exposes its state through getters that read the
    // observer's own signals. React re-renders a `QueryContent`'s parent on
    // every state change; Angular only re-checks a view something marked, and
    // the parent's `[query]="query"` binding reads none of those signals. Read
    // them here, in an effect, so a changed document marks this region for
    // check exactly when React would re-render it. A replaced `query` prop
    // re-subscribes the same effect to the new observer.
    effect(() => {
      const query = this.observer()
      void query?.data
      void query?.status
      void query?.error
      void query?.isPreviousData
      untracked(() => {
        this.update()
        this.changeDetector.markForCheck()
      })
    })
  }

  /**
   * The branch the current query state shows.
   * @returns The template and its context, or nothing.
   */
  private branch(): Branch {
    const query = this.query
    const identified = typeof this.getRecordId === 'function'
    if (
      query?.data === undefined ||
      (query.isPreviousData &&
        (identified ||
          this.recordKey !== undefined ||
          query.data === null ||
          this.empty?.when(query.data)))
    ) {
      if (query?.status === 'error' && this.error) {
        const error = query.error ?? new Error('The query failed without an error.')
        return { template: this.error, context: { $implicit: error, a0: error } }
      }
      return { template: this.pending ?? null, context: {} }
    }
    if (query.data === null) return { template: this.missing ?? null, context: {} }
    const identifiedTemplate = identified ? this.children : null
    if (identified) {
      const id = this.recordIdentity()
      // No identity means no record-specific action: the branch stays pending.
      if (id === undefined) return { template: this.pending ?? null, context: {} }
      if (this.empty?.when(query.data))
        return { template: this.empty.render, context: { $implicit: query.data, a0: query.data } }
      return {
        template: identifiedTemplate,
        context: { $implicit: query.data, a0: query.data, a1: id },
      }
    }
    if (this.empty?.when(query.data))
      return { template: this.empty.render, context: { $implicit: query.data, a0: query.data } }
    return { template: this.children, context: { $implicit: query.data, a0: query.data } }
  }

  /**
   * The loaded document's verified identity, when `getRecordId` is set: absent,
   * null and an empty string are no identity.
   *
   * @returns The nonempty ID, or `undefined` without one.
   */
  private recordIdentity(): string | number | undefined {
    const getRecordId = this.getRecordId
    if (typeof getRecordId !== 'function') return undefined
    const data = this.query?.data
    if (data === undefined || data === null) return undefined
    const id = getRecordId(data as NonNullable<T>)
    return id == null || id === '' ? undefined : id
  }

  /**
   * Follows a replaced `query` prop: the reactivity effect subscribes to the
   * new observer's own signals on its next run.
   */
  ngOnChanges(): void {
    this.observer.set(this.query)
  }

  /**
   * Mounts the branch the query state shows, and refreshes the mounted view's
   * context when the state changes. Runs on every change-detection pass, so an
   * input set by a host binding is always folded in before this runs.
   */
  ngDoCheck(): void {
    this.update()
  }

  /**
   * Shows the branch the current query state describes: a different template —
   * or a changed record identity — replaces the mounted view, and a changed
   * document (or error) is written into the context the mounted view reads.
   * Replacing the view on a `recordKey` or ID change mounts the record's own
   * state (an edit form) fresh, the way React's keyed Fragment does.
   */
  private update(): void {
    const next = this.branch()
    const id = this.recordIdentity()
    const recordChanged = this.recordKey !== this.mountedRecord || id !== this.mountedId
    if (next.template !== this.current || recordChanged) {
      this.view?.destroy()
      this.view = undefined
      this.current = next.template
      this.mountedRecord = this.recordKey
      this.mountedId = id
      if (next.template) this.view = this.outlet.createEmbeddedView(next.template, this.context)
    }
    for (const key of Object.keys(this.context)) {
      if (!(key in next.context)) delete this.context[key]
    }
    Object.assign(this.context, next.context)
    this.view?.markForCheck()
  }
}

Functions

prefetchQuery(options)

Warms the cache for a document, when the connection can afford it (see shouldPrefetch() in the core). Safe to call repeatedly: a fresh or in-flight document is skipped, and failures are swallowed.

function prefetchQuery<T>(options: QueryOptions<T>): void
  • options — Key, fetch, freshness.

createQueryResource(config)

Describe one API resource once and get its reads and writes on the shared cache.

A page that loads with fetch inside an effect and mirrors the answer into useState has to re-solve the same problems on every screen: a late answer for the previous page lands over the current one, and a list still shows what it showed before a comment was added. Here the reads are useQuery options (one key per viewer, page and filter; the previous rows stay until the next answer) and every write puts the server's own record into the cache and fetches the lists on screen again.

The factory supplies data operations. Mount a keyed control inside QueryContent (your framework's query package: @molecule/app-query-react, -vue, …) so it receives a loaded record and stays mounted during refresh. For a server-backed toggle, use useOptimisticValue from your framework binding (@molecule/app-react, @molecule/app-vue, …), or OptimisticToggleButton from its UI package (@molecule/app-ui-react, …) for a boolean. Pass toggle as its commit adapter, return the saved flag/count, and render the controller's value for the action label too. Do not block clicks while that commit is pending. The resource example in @molecule/app-query-react composes these APIs; a custom handler must provide the same readiness and ordering itself.

Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client and the query provider are whatever the app bonded.

function createQueryResource<T, Create = Partial<T>, Update = Partial<T>>(
  config: QueryResourceConfig<T>,
): QueryResource<T, Create, Update>
  • config — The resource's name, path, HTTP client and response readers.

Returns: List and detail query options, and create, update, remove, toggle and refresh.

useListQuery(route, inputs, read)

Observe the page a URL list route points at. read builds the query from the current value of each input (the signed-in viewer, request params, a parent record's id) and the route's filters, page size and offset. The query is disabled (null, no request) while viewer is null (auth is still being restored) or the route cannot load yet; a changed input or URL moves the same observer to the new page. Call it in an injection context, as useQuery.

function useListQuery<T, Values extends { viewer: string | null }, Filter extends string = string>(
  route: ListQueryRoute<Filter>,
  inputs: ListQueryInputs<Values>,
  read: (values: Values & { viewer: string }, list: ListQueryState<Filter>) => QueryOptions<T>,
): UseQueryResult<T>
  • route — The list route, usually useListRoute(...) from @molecule/app-angular.
  • inputs — Plain values or signals; viewer is the signed-in user's id, 'anonymous', or null while auth is restoring.
  • read — Builds the page's query options, e.g. a generated articlesPage(...).

Returns: The query state, as useQuery returns it.

usePrefetch()

A stable prefetch(options) function for event handlers. Call it in an injection context (a component field initializer or constructor); the returned function is one object for the component's lifetime.

function usePrefetch(): <T>(options: QueryOptions<T>) => void

Returns: The prefetch function.

intentPrefetchProps(options)

Handlers that warm a document at the first sign of intent: the pointer arriving, keyboard focus, or a touch starting. Put them on a link's host bindings (each property is named after the DOM event it warms on):

host: { '(pointerenter)': 'prefetch.pointerenter()', '(focus)': 'prefetch.focus()' }

It is a plain function (not a hook), so it works inside @for loops too.

function intentPrefetchProps<T>(options: QueryOptions<T>): IntentPrefetchProps
  • options — Key, fetch, freshness.

Returns: The handlers.

useQuery(options)

The document for the options' key, kept current: cached data is read on the very first render (so a warmed page never flashes a loading state), a stale or missing document is fetched, and every change re-renders the template that reads the result. Pass null to observe nothing. A key change resets to that key's state; the hook never hands a caller another key's document — unless the caller opts into QueryOptions.keepPreviousData, and then only within one QueryOptions.principal.

The request is stable across template refreshes — a parent state change neither restarts it nor cancels it, so a response that arrives after one still lands. It is aborted only when the key changes or the component is destroyed (the signal given to options.fetch). Use this instead of a hand-written effect + fetch: an effect whose cleanup sets a cancelled flag, and whose tracked dependencies include a function rebuilt each run, cancels its own request on every run and then skips the refetch. An explicit refetch() is an awaited cache fetch; it can finish after the observer is destroyed, like an explicit client.fetch(options) caller.

For a LIST, put the route's page, filter and selected view in the key and pass keepPreviousData with a principal: a Next/Previous or filter change then keeps the rows already on screen until the new page answers, instead of rendering a loading state over an empty list. The key names everything the answer depends on, and the app's HTTP client sends the session, so a list the server can filter or personalize per viewer puts the viewer in its key and passes the same value as principal ('anonymous' when signed out): an account switch then drops the previous account's document immediately. Only an endpoint that answers every viewer the same takes a viewer-free key with principal: 'public'.

For custom mutation handlers, setData(saved) publishes the server's response to this key and every observer. Use setData(current => next) for a local cache update. Render data directly; a component-local copy stops observing later server responses. Prefer createQueryResource when the API's reads and writes can share one resource definition. Mount record-dependent actions inside QueryContent (or an explicit non-null data branch), so a visible action cannot return early because its initial record is still missing. Keep loaded actions mounted during refreshes. Server-backed toggles use OptimisticToggleButton from @molecule/app-ui-angular (or useOptimisticValue from @molecule/app-angular in a control that is re-created per record) to keep their displayed label and queued clicks on the same state while a save finishes.

function useQuery<T>(options: QueryOptionsInput<T>): UseQueryResult<T>
  • options — Key, fetch, freshness, and optionally principal with keepPreviousData; or null; or a signal of either (the options a component recomputes on its own state — every change is followed on the same instance).

Returns: The document's state, setData() and refetch(). isPreviousData is true while data is the previous key's document for the same principal.

Injection Notes

Requirements

Peer dependencies:

  • @angular/common ^22.0.0
  • @angular/core ^22.0.0
  • @angular/platform-browser ^22.0.0
  • @molecule/app-angular ^3.13.0 || ^4.0.0
  • @molecule/app-query ^1.4.0

Runtime Dependencies

  • @angular/common

  • @angular/core

  • @angular/platform-browser

  • @molecule/app-angular

  • @molecule/app-query

  • useQuery reads the cache synchronously on the first render. A document prefetched from a hovered link, or seeded with client.set() from a server-rendered JSON island, renders at once — no spinner, no layout shift. Render loading from status === 'idle' || status === 'loading'; undefined data can also accompany a completed error. A completed null response is missing, not pending. The detail example treats only HTTP 404 or a successful null response as missing; other errors stay load failures. The app's bonded HTTP client rejects non-2xx responses. Native fetch resolves them, so a custom fetcher must check response.ok before JSON.

  • Mount a detail region and its actions only after its initial document arrives. A visible container is not a loaded document: a caller may wait for that container and read its text once, or click its button, while data is still undefined. Put the loading message outside the detail region, as in PackagePage above. Keep record-dependent controls absent or natively disabled until the record exists; returning early inside an enabled click handler loses that click. client.set() protects a cache mutation from an older read, but cannot recover a click whose handler never sent the mutation.

  • The key is the identity. Building the options inline inside a computed is fine; the hook resubscribes only when the key's value changes, not when the fetch closure does.

  • A key change normally resets to the new key's state. For a list's own page/filter/view change, opt into keepPreviousData with a principal; isPreviousData tells you the rows on screen belong to the key you just left. A completed response (including an empty list) replaces them, and a changed principal drops them, so an account switch never shows the previous account's rows. Do not emulate this with a component-local copy of the query data — that mirror is what serves stale rows under a new page, or blanks the list on a re-render.

  • The key names the viewer whenever the answer can depend on it. The app's HTTP client sends the session, so the server may filter or personalize even a list that guests can see (a favorited or following flag), and the cache serves a key's document to whoever observes it, across sign-in and sign-out. Key such a list on the viewer (user ? String(user.id) : 'anonymous'), pass the same value as principal, and pass null while the session is still being restored (status === 'loading'; the HTTP client holds the request until then anyway), so restoring a session never swaps a key that already rendered rows. A viewer-free key with principal: 'public' is only for an endpoint that answers every viewer the same. A protected route view also passes null while it cannot load yet.

  • Render loading, empty and error status outside the item list, and never give a placeholder the item's own class or element shape: a list read by the item class (or by :first-child) must contain only real items. An empty array is a loaded empty state, not a missing response; render it only when isPreviousData is not set, because a retained document belongs to the key you just left.

  • intentPrefetchProps returns three handlers named after the DOM events an Angular template binds (pointerenter, focus, touchstart). It is a plain function (not a hook), so it works inside @for too.

  • Prefetching respects the browser's data-saver setting and skips 2G connections (shouldPrefetch() in the core) — do not bypass that for "important" links; the person can still click.

  • Refresh a mounted document with query.refetch(). It fetches even a fresh cache entry and updates every observer of that key. After a mutation whose response is not the whole document, await query.refetch() reloads the displayed list. It resolves with the resulting state (including status: 'error' on failure); a disabled query stays idle. Prefer client.set(key, response) when the mutation already returned the whole document.

  • Errors are not thrown from the hook; read status === 'error' and error. client.invalidate() does NOT refetch a mounted page — it only marks documents stale, so the page keeps its error (or its old document) until the app retries with client.fetch(options) or the page subscribes again (a key change or a re-mount).

  • After a mutation, client.set(key, response) paints the server's own answer at once and supersedes an older fetch already in flight for that key, so its response cannot undo the mutation. An existing fetch() caller still settles independently of the cache write; read client.get(key) for the newest document. client.invalidate(prefix) marks the affected reads stale for their next mount. Which key and which scope is the app's decision: the cache does not infer it from auth or form state.

  • The result's state fields are signals read through plain properties (query.data, query.isPreviousData), so a template binding that reads them re-renders when the document changes, and the object can be handed to QueryContent's query input unchanged.

Render resource-dependent lists and controls through QueryContent. Its children template receives only loaded, non-null data; loading and error content never mount item actions. It renders cached content during refresh and treats an empty list, false and zero as data. Put the list, or the record's own container (its card, header or profile block), inside the children template and every status line (loading, error, isFetching refresh) beside it, never inside it: a reader that finds the container and reads its paragraph must read the record, not "Loading…".

Keep every resource identity in the query key. A boundary cannot correct a query that supplies another record's cached data. For a list, map real rows inside the children template; never style a status placeholder as a row.

For a collection, QueryContent also accepts one empty branch: { when: page => page.rows.length === 0, render: page => selectedEmptyState }. It is exclusive with loaded children, so a selected view chooses its message and recovery action once rather than rendering a general empty message beside it. when receives a loaded document; empty arrays remain data when this prop is omitted. The render value uses this framework's existing children function, snippet or template.