Loading...
Loading...
ALWAYS use when working with TanStack Query (Angular Query) for server state management, data fetching, caching, or mutations in Angular applications.
npx skill4agent add oguzhan18/angular-ecosystem-skills angular-queryinjectQueryinjectMutationnpm install @tanstack/angular-query-experimentalimport { provideHttpClient } from '@angular/common/http';
import { provideTanStackQuery } from '@tanstack/angular-query-experimental';
import { QueryClient } from '@tanstack/query-core';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(),
provideTanStackQuery(new QueryClient())
]
};import { injectQuery } from '@tanstack/angular-query-experimental';
@Component({})
export class TodosComponent {
private http = inject(HttpClient);
query = injectQuery(() => ({
queryKey: ['todos'],
queryFn: () => lastValueFrom(this.http.get<Todo[]>('/api/todos'))
}));
}@Component({
template: `
@if (query.isPending()) {
Loading...
} @else if (query.isError()) {
Error: {{ query.error().message }}
} @else {
@for (todo of query.data(); track todo.id) {
{{ todo.title }}
}
}
`
})
export class TodosComponent {
query = injectQuery(() => ({ ... }));
}import { injectMutation, injectQueryClient } from '@tanstack/angular-query-experimental';
@Component({})
export class AddTodoComponent {
private http = inject(HttpClient);
private queryClient = injectQueryClient();
mutation = injectMutation(() => ({
mutationFn: (newTodo: string) =>
lastValueFrom(this.http.post('/api/todos', { title: newTodo })),
onSuccess: () => {
this.queryClient.invalidateQueries({ queryKey: ['todos'] });
}
}));
addTodo(title: string) {
this.mutation.mutate(title);
}
}@Injectable({ providedIn: 'root' })
export class TodoService {
private http = inject(HttpClient);
getTodoOptions = (id: number) => queryOptions({
queryKey: ['todo', id],
queryFn: () => lastValueFrom(this.http.get(`/api/todos/${id}`))
});
}
@Component({})
export class TodoComponent {
private todoService = inject(TodoService);
todo = this.todoService.getTodoOptions(1);
}query = injectQuery(() => ({
queryKey: ['todos'],
queryFn: () => fetchTodos(),
retry: 3,
staleTime: 1000 * 60 * 5, // 5 minutes
refetchOnWindowFocus: false
}));mutation = injectMutation(() => ({
mutationFn: createTodo,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['todos'] });
}
}));mutation = injectMutation(() => ({
mutationFn: updateTodo,
onMutate: async (newTodo) => {
await queryClient.cancelQueries({ queryKey: ['todos'] });
const previousTodos = queryClient.getQueryData(['todos']);
queryClient.setQueryData(['todos'], (old: Todo[]) => [...old, newTodo]);
return { previousTodos };
},
onError: (err, newTodo, context) => {
queryClient.setQueryData(['todos'], context.previousTodos);
}
}));