0.0.3 • Published 6 months ago
ts-rest-ng v0.0.3
TsRestNg
Installation
npm i ts-rest-ng
Usage
- Create a ts-rest contract as you normally would
const c = initContract();
export const todoContract = c.router({
getTodos: {
method: 'GET',
path: '/todos',
responses: {
200: z.array(z.string()),
},
summary: 'Get all todos',
},
});
- Create an injection token in your angular app
// create an injection token for the client
export const TodoClient = new InjectionToken<inferNgClient<typeof todoContract>>('todo-client');
- Add the client as a provider somewhere in your app
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(),
{
provide: TodoClient,
useFactory: () =>
initNgClient(todoContract, {
baseHeaders: {},
baseUrl: 'http://localhost:3333',
}),
},
],
};
- Start using the client
@Component({
template: `
<ul>
<li *ngFor="let todo of todos$ | async">
{{ todo }}
</li>
</ul>
`,
imports: [CommonModule],
standalone: true,
})
export class TodoComponent {
private todoClient = inject(TodoClient);
todos$ = this.todoClient.getTodos().pipe(map((res) => (res.status === 200 ? res.body : [])));
}