Answer the question
In order to leave comments, you need to log in
How to correctly track changes in service data and render them in a component?
There is a component that works with the TableService service. When a button click is fired and the actionHandler() function is called, the corresponding service method must be fired, which changes the state of the programmers, which is stored in the service. How is the data state change tracked in the Angular component? If you notice that I wrote something wrong somewhere here, I'll ask you to correct me, since I'm completely new to Angular. Learn Angular with Documentation
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.scss'],
providers: [
TableService
]
})
export class TableComponent {
displayedColumns: Array<String> = ['id', 'Firstname', 'Lastname', 'Middlename', 'Position', 'Date Of Birth', 'Active', 'operations'];
dataSource: Array<Programmer> = this.tableService.getData();
constructor(private bottomSheet: MatBottomSheet, private tableService: TableService) {
}
actionHandler(action: string, element?: Programmer): any {
if (action === ActionType.EDIT) {
console.log(element);
const options = new MatBottomSheetConfig();
options.data = {element};
return this.bottomSheet.open(PopupComponent, options);
}
if (action === ActionType.ADD) {
return this.bottomSheet.open(PopupComponent);
}
return;
}
getData(): void {
this.dataSource = this.tableService.getData();
}
remove(id: number): void {
this.tableService.remove(id);
this.getData();
}
}
@Injectable({
providedIn: 'root'
})
export class TableService {
private programmers: Programmer[] = [
{
id: 1,
firstName: 'Павел',
lastName: 'Петров',
middleName: 'Валериевич',
position: Position.JUNIOR,
dateOfBirth: 'Thu Mar 10 2022 00:00:00 GMT+0600 (Омск, стандартное время)',
active: true
},
{
id: 12,
firstName: 'Павел',
lastName: 'Петров',
middleName: 'Иванович',
position: Position.JUNIOR,
dateOfBirth: 'Thu Jul 16 1998 00:00:00 GMT+0700 (Омск, летнее время)',
active: true
},
{
id: 13,
firstName: 'Павел',
lastName: 'Петров',
middleName: 'Петрович',
position: Position.SENIOR,
dateOfBirth: '11/01/2001',
active: true
}
]
constructor() {
}
getData(): Array<Programmer> {
return this.programmers;
}
remove(id: number) {
this.programmers = this.programmers.filter(programmer => programmer.id !== id);
}
add(programmer: Programmer) {
this.programmers.push(programmer);
console.log('added new programmer', this.programmers);
}
edit(id: Programmer) {
this.programmers.map((el, index) => {
if (el.id === id.id) {
this.programmers[index] = id;
return;
}
return;
});
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question