Angular 2: Issue with data table not updating after item deletion

I need assistance with updating a data table after deleting an item. The database is updated correctly when I delete an item, but the table does not automatically refresh to reflect the changes.

managenews.component.ts

import { Component, OnInit } from '@angular/core';
import {NewsService} from "../../../services/news.services";
import {News} from "../../../entities/news";
import {Subscription, Observable} from "rxjs";
import {ActivatedRoute} from "@angular/router";

@Component({
  selector: 'app-managenews',
  templateUrl: './managenews.component.html',
  styleUrls: ['./managenews.component.css'],
  providers: [NewsService]

})
export class ManagenewsComponent implements OnInit {


  news: News[]= new Array();
  newsSub:Subscription;
  constructor(private newsService: NewsService,private route: ActivatedRoute) { }

  ngOnInit() {
    this.getNews();
  }

  getNews(){
    this.newsSub=this.newsService.GetAllNews().subscribe(news =>this.news = news);
  }


   deleteNews (id:number){
     this.newsService.GetById(id).subscribe((e)=>{
        let n=<News> e;
         this.newsSub= this.newsService.deleteNews(n).subscribe(e=>{
          this.getNews();
        });
    });
   }

  ngOnDestroy(){
    this.newsSub.unsubscribe();
  }
}

managenews.component.html

  <table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%>
<tr>
  <td>Title</td>
  <td>Date of creation</td>
  <td>Author</td>
  <td>Location</td>
  <td>Edit</td>
  <td>Delete</td>
  <td>Upload Media</td>
</tr>


<tr *ngFor="let n of news">
  <td>{{n.title}}</td>
  <td>{{n.dateOfCreation}}</td>
  <td>{{n.author}}</td>
  <td>{{n.location}}</td>
  <!--action buttons-->
  <td class="aligne"><a [routerLink]="['editnews', n.id]"><i class="fa fa-pencil-square" aria-hidden="true"></i></a></td>
  <td  class="aligne"><a [routerLink]="['./']"(click)="deleteNews(n.id)" ><i class="fa fa-trash" aria-hidden="true"></i></a></td>
  <td  class="aligne"><i class="fa fa-upload" aria-hidden="true"></i></td>
</tr>

I'm looking for help on how to refresh the table after deleting an item.

Answer №1

It appears that upon deleting an item, the backend fails to generate a JSON response, leading to a HttpErrorResponse.

ERROR HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "", ok: false, …}

To address this issue, I included responseType: 'text' in httpOptions within my news.services.ts:

import {HttpHeaders, HttpClient, HttpErrorResponse} from "@angular/common/http";
import {Observable} from "rxjs";
import 'rxjs/add/operator/catch';
import {News} from "../entities/news";
import {Injectable, Injector} from "@angular/core";
import {Router} from "@angular/router";
import {Country} from "../entities/Country";

@Injectable()
export class NewsService {

  private router: Router;

   header: HttpHeaders;

  httpOptions = {
    headers : new HttpHeaders({ 'Content-Type': 'application/json'}),
    responseType: 'text'
  };
  createAuthorizationHeader(headers: Headers) {
    headers.append('Authorization', this.token);
    headers.append('Content-Type', "application/json");
  }
  constructor(private http: HttpClient,private injector:Injector) {

    this.router = this.injector.get(Router);
    this.header = new HttpHeaders();
    this.header.set('Authorization', this.token);
    this.header.set('Content-Type', 'application/json');

  }

  public GetById(id: number) : Observable<any|News>{
       /*****/
  }

  public updateNews(n: News) {
    return this.http.put(this.url, JSON.stringify(n),this.httpOptions);

  }

  public deleteNews(n: News) {
    return this.http.delete(this.url + '/' + n.id, this.httpOptions);
  }

}

This adjustment proved successful in resolving the issue!

A huge thanks to all those who offered their assistance...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered when attempting to convert Angular application to Angular Universal

While attempting to convert my Angular App into Angular Universal, I encountered an issue. I used the command "ng add @nguniversal/express-engine --clientProject my-app" An error occurred: Module not found - '@schematics/angular/utility/json-file&apo ...

What is the best way to trigger a method after an old component has been removed from the DOM while navigating within Angular

I am facing a challenge where I need to execute a method on ComponentB after a routerLink is clicked, causing the navigation from ComponentA to ComponentB. It is crucial that this method is triggered only after the entire navigation process is complete (i. ...

Elevate your Material UI Avatar with an added level of

Attempting to give a MUI Avatar component some elevation or shadow according to the documentation provided here. <Avatar alt="Cindy Baker" src="/static/images/avatar/3.jpg" /> Enclosing the Avatar within a paper or Card element increases the size o ...

Error message: Unable to instantiate cp in Angular 17 application while building with npm run in docker container

After creating a Dockerfile to containerize my application, I encountered an issue. When I set ng serve as the entrypoint in the Dockerfile, everything works fine. However, the problem arises when I try to execute npm run build. Below is the content of my ...

Add the specified HTML tag to the existing document. An error has occurred: HierarchyRequestError - The action would result in an invalid node

During my testing of a React/TypeScript project using Jest + Enzyme, I encountered an issue when trying to append an HTML tag. The error occurred with the following unit test code: const htmlTag: HTMLElement = document.createElement('html'); htm ...

Having trouble retrieving documents from a nested collection in Firebase

I am attempting to retrieve all documents from Firebase that are based on a query. Here is my current firebase structure: https://i.stack.imgur.com/tXrX8.png Even though I have two documents inside the "ListaFavorite" collection, when I check using empty ...

Unexpected behavior: Angular4/Javascript Date object alters when timezone is specified in Date constructor

In my Angular 4 application, I encountered an issue with a date retrieved from an API call. The date is in the format '1990-03-31T23:00:00-06:00' and when attempting to create a Date object and retrieve the month using getMonth(), it returns the ...

Guide to iterating through an Observable<Object[]> to generate an array of objects

Google Firestore collection named users is structured as follows : { "contactNumber":"0123456789", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88e2e7e0e6ece7edc8efe5e9e1e4a6ebe ...

Embed the div within images of varying widths

I need help positioning a div in the bottom right corner of all images, regardless of their width. The issue I am facing is that when an image takes up 100% width, the div ends up in the center. How can I ensure the div stays in the lower right corner eve ...

How can I inform Typescript that an interface will exclusively consist of defined members?

My interface looks like this interface Person { name?:string; age? :number; gender?:string } I need to reuse the same interface type, but with a modification indicating that all members will never be undefined. The updated version would look like this: ...

Struggling to properly interpret and process the latest data being sent from an Angular single page application (SPA

Currently, I am developing a Single Page Application that utilizes Angular 8 on the frontend and Laravel on the backend. The application involves performing CRUD operations, and specifically when dealing with editing functionality, I encounter an issue. Th ...

TypeScript version 3.7 has implemented a new feature where it will now display errors for each individual invalid prop instead of grouping them together as it

Scenario using TypeScript 3.5.3 https://i.stack.imgur.com/wykd6.png link to interactive playground - TS 3.5.3 demo running successfully Example with TypeScript 3.7.2 https://i.stack.imgur.com/BPckB.png link to demo - TS 3.7.2 demo not functioning correctl ...

ngFor is failing to show the array data, which is being fetched from Firebase

Hi there, I understand that this question has been asked frequently, but the regular solutions are not working for me. ts handleChangeFormType(formType) { this.serverData.getData('questionnaire/' + formType) .subscribe( (response: Respons ...

I'm encountering a ModuleNotFoundError that says: "Module not found: Error: Can't resolve". What could be causing this

I have encountered an issue while trying to create a blog post page on my NextJS website. The page displays correctly on my local machine, but when I deploy it to production, I am facing the following error and I am unsure of how to resolve it: Here is the ...

Ways to manage an rxjs observable reaction that may potentially have no data?

Currently, I am working with Angular2 and Ionic2 using typescript and have a requirement to manage responses from the backend service. The response may either be empty with http status 200 or it could be a json object containing an error message property ...

Building a resolver to modify a DynamoDB item via AppSync using the AWS Cloud Development Kit (CDK)

After successfully creating a resolver to add an item in the table using the code provided below, I am now seeking assistance for replicating the same functionality for an update operation. const configSettingsDS = api.addDynamoDbDataSource('configSet ...

Can you guide me on how to access an Angular route using a URL that includes query parameters?

Within my current development project, I have implemented a user profile route that dynamically navigates based on the user's _id. This means that when a user accesses the page, their _id is stored in localStorage and then used to query MongoDB for th ...

How can I retrieve properties from a superclass in Typescript/Phaser?

Within my parent class, I have inherited from Phaser.GameObjects.Container. This parent class contains a property called InformationPanel which is of a custom class. The container also has multiple children of type Container. I am attempting to access the ...

Navigate to the previous page

What is the best way to navigate back to the last page in Angular 2? Can it be done like this? this._router.navigate(LASTPAGE); For instance, if page C includes a Go Back button, From Page A to Page C, clicking it will take you back to Page A. Fro ...

What should I do to resolve the error when "HttpClient" name is not found?

Whenever I attempt to start my project using npm start, I encounter an error: [at-loader] Checking completed with 1 error [at-loader] ./node_modules/@ngx-translate/http-loader/src/http-loader.d.ts:10:23 TS2304: Cannot find name 'HttpClient' ...