fromAsync
fromAsync
is a utility function designed to simplify asynchronous data handling when working with Angular signals using observables. It takes an observable as input and returns an object containing signals for loading, data, and error states along with a "refresh" function.fromAsync<DataType, ErrorType>(observable$: Observable<T>, options: FromAsyncOptions<T>): FromAsyncResponse<DataType, ErrorType>
Parameters
observable$ | The observable to be monitored for data loading and error handling. |
options | The combination of CreateEffectOptions and CreateSignalOptions andinitialValue* which represent the value of data signal until the fetch is completed successfully. |
Returns FromAsyncResponse
loading: Signal<boolean> | A signal that indicates whether the operation is in progress. |
data: Signal<DataType> | A signal that emits the data when the operation is successful. |
error: Signal<ErrorType> | A signal that emits an error message when the operation encounters an error. |
refresh: function | A function that allows you to manually trigger a data refresh |
Example
Fetch and Mutate Todos
private todoService = inject(TodoService)
private obs$: Observable<Todo[]> = this.todoService.getTodos$();
readonly query = fromAsync(this.obs$, { initialValue: [] });
constructor() {
effect(() => {
const error = this.query.error();
if (error) {
// do something with error
}
});
}
saveChanges() {
this.todoService.saveTodos(this.query.data()).subscribe(() => this.refresh())
}
refresh() {
this.query.refresh();
}
mutateData(id: string) {
this.query.data.mutate((todos) => {
const todo = todos.find((x) => x.id === id);
todo.completed = !item.completed;
});
}