Angular 19 introduces Resource, an async signal, typically used for web requests. I find it reminiscent of TanStack Query but more minimalist and signal based. While RxResource works great with Angular HTTPClient, the regular “Resource” works with good old fetch. Which means we can combine it with openapi-typescript and openapi-fetch. The result will let us quickly grab typed API resources and process them with Angular Signals, no rxjs needed.
Follow openapi-fetch’s documentation to install and generate your openapi types. I called mine src/app/api/api-schema.d.ts. Then create a file such as src/app/api/api.ts
import createClient from "openapi-fetch";
import type { paths } from "./api-schema";
export const client = createClient<paths>();
Let’s imagine fetching a Foo api in a Service.
export class FooService {
foosResource = resource({
loader: async () => {
const { data, error } = await client.GET("/api/foo/");
// Consider error handling here
return data
})
foos = computed(() => this.foosResource.value() || [])
}
Our foos will be typed according to the openapi spec. We can also refer to the types directly:
import type { components } from "src/app/api/api-schema";
type Foo = components["schemas"]["FooSchema"];
With this approach, we can easily get typed API data into Angular and it looks more like any other JS framework code.
Leave a comment