I'm trying to use new angular "feature" - signals. Inside some service I have a signal:
failedTasks = computed(() => this.tasksState().failedTasks);
And then, I want to connect that signal to the table data source inside component. Previously, using observables, the code was like that:
dataSource = new MatTableDataSource<FailedTask>([]);
constructor(tasksService: TasksService){
this.tasksService.failedTasks$.subscribe(tasks => this.dataSource.data = tasks)
}
but with signals I have no idea how to do the same except using "effect" like that:
constructor(tasksService: TasksService) {
effect(() => {
this.dataSource.data = this.tasksService.failedTasks();
});
}
What do you think about this approach? According to official docs "Effects are rarely needed in most application code", but how to implement the logic when we need to subscribe some source inside component.ts?
Maybe this could be a solution:
export class MyComponent implements AfterViewInit {
displayedColumns: string[] = ['col1', 'col'];
dataSource = computed(() => {
const notifications = this.store.notifications();
const table = new MatTableDataSource(notifications);
this.setSortingAndPagination(table);
return table;
});
@ViewChild(MatSort) sort: MatSort;
@ViewChild(MatPaginator) paginator: MatPaginator;
store = inject(NgrxStore);
ngAfterViewInit(): void {
this.setSortingAndPagination(this.dataSource());
}
setSortingAndPagination(dataSource: MatTableDataSource<Notification>): void {
dataSource.sort = this.sort;
dataSource.paginator = this.paginator;
}
}
<div class="mat-elevation-z8">
<table mat-table [dataSource]="dataSource()" matSort>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With