Angular: how update the Frontend after deletion of one item, in a nested component

Discussão em 'Angular' iniciado por ncasteln, Dezembro 30, 2024.

  1. ncasteln

    ncasteln Guest

    I am using Angular18 and I have this scenario, which I'll try to simplify as much as possible.

    • The DataService handles http requests, using HttpClient:


    export class DataService {
    constructor(private http: HttpClient) {}
    getAll() {}
    deleteOne() {}
    }


    • The DataComponent is a wrapper which uses the DataService to retrieve the data, and display it.


    export class DataComponent implements OnInit {
    data: Data[] = []
    constructor(private dataService: DataService) {}
    ngOnInit(): void {
    this.dataService.getAll().subscribe(data => { this.data = data }
    }
    }


    • Inside the DataComponent.html I have a <FooComponent /> which recieves a single data.


    @for ( item of data; track $index ) {
    <FooComponent [item]="item" />
    }


    • Inside the FooComponent.html I have another component, the ItemActions component.


    <h1>{{ item.name }}</h1>
    <item-actions [item]="item" />


    • The ItemActions holds some buttons and one of them is the delete button, which would trigger the deleteOne() function of the DataService.


    export class ItemActions {
    constructor(private dataService: DataService) {}
    onDelete( id: string ) {
    this.dataService.deleteOne(id) // etc.
    }
    }



    Given this scenario the backend works fine: the http DELETE request is performed, but the Frontend is not updated accordingly. Some ideas:


    • I think the problem could be solved with RxJS but since I am new on the topic, I cannot understand how. I would really appreciate a suggestion on this topic and eventually a VERY good RxJS tutorial applied to Angular.


    • I was thinking about EventEmitter, but in this case I should emit something to the DataComponent to suggest that something was deleted and therefore refresh the page. But if I have multple and multiple nesting, then this would be a very long chain of emitters.


    • I think I could also use ChangeDetectionRef, but I'd prefer the RxJS approach to handle the problem.

    Continue reading...

Compartilhe esta Página