Search code examples
angularrestrefreshcrud

Angular CRUD - Refresh UI after add/update/delete operation


I was wondering that it is better to refresh the UI when executing an add/update/delete operation from a CRUD in Angular.

The options are as follows (for example, for delete action):

1. Update local variable with previously fetched data after perform the action.

deleteProduct(id) {
    this.productsService.deleteProduct(id).subscribe(status => {
        this.products = this.products.filter(item => item.id != id);
    });
}

2. Fetch the items again calling REST API.

deleteProduct(id) {
    this.productsService.deleteProduct(id).subscribe(status => {
        this.getProducts();
    });
}

getProducts() {
    this.productsService.getProducts().subscribe(products => {
        this.products = products;
    });
}

This would also be applicable to add or edit, with more code obviously.

Which option is better in terms of good practices and performance? Updating variable data locally or performing a new http request to obtain updated data.


Solution

  • I think, It can depend on your project . I use the following flow in my project (client[Angular] should follow the server)

    (Here I use WEB API)

    To create : It's better to return the created Item as below

    [HttpPost]
    public ActionResult Post(Item item)
    {
        if (everything is ok)
        {
            // resourceUrl: the address of the source that we have just created
            return Created(resourceUrl, item);
        }
    
        if (there is an error) {
            return BadRequest();
        }
    }
    

    To Edit : You do not need to return any Item, you should return the status code (400[BadRequest], 200[OK], 204[NoContent] and so on) like the following :

    [HttpPut("{id}")]
    public ActionResult Put(Item item, int id)
    {
        var existingItem = (retrive item form db based on id); 
        if (existingItem == null) {
            return BadRequest("Cannot update ...");
        } else {
            // update operation here ...
            return Ok();
        }
    }
    

    To delete - you should return the status code (400[BadRequest], 200[OK], 204[NoContent] and so on)

    EDIT:

    You don't have to follow above recommendation. You can select the first suggestion in your question (Update local variable with previously fetched data after perform the action.) , It depends on your project.