Deleting a post will only occur upon refreshing the page, while activating a subscription and removing the post will occur after refreshing

Currently, I am following coursework where I have successfully implemented a delete function that removes data from the node server. The setup involves an Angular frontend connected to a MongoDB database.

The code for the 'deletePost' function in the Angular service:

deletePost(postId: string) {
        this.http
          .delete('http://localhost:3000/api/posts/' + postId)
          .subscribe(() => {
            console.log('deleted');
            const updatedPosts = this.posts.filter(post => post.id !== 
                  postId);
            this.posts = updatedPosts;
            this.postsUpdated.next([...this.posts]);
       });
     }

For the Angular front end:

onDelete(postId: string) {
    console.log('deleted');
    this.postsService.deletePost(postId);

After testing the functionality, it seems that upon clicking the delete button for the first time, the action is initiated visually but no data deletion occurs until a page refresh and subsequent attempt. Despite seeing the 'deleted' log from the frontend, the actual post removal process only triggers on the second attempt.

Regarding the deletion process on the node server side:

app.delete('/api/posts/:id', (req, res, next) => {
      Post.deleteOne({ _id: req.params.id }).then(result => {
         res.status(200).json({ message: 'Post deleted' });
      });
    });

How can this issue be resolved effectively?

Could the delay in immediate deletion perhaps hint at a waiting period or specific order of operations needed for proper execution? Consider adding additional instructions or validations to streamline the deletion process.

Answer №1

To ensure proper functionality, it is important to subscribe to the service in the onDelete Method rather than within the service itself. Within the Service, return the http Delete Request as an Observable.

Below is an example code snippet for clarification: Define your DeletePost Method in the Service

deletePost(postId: string) :Observable<any> {
        return this.http.delete('http://localhost:3000/api/posts/' + postId);
}

In your component .ts file:

onDelete(postId: string) {
    this.postsService.deletePost(postId).subscribe(()=>{
        console.log("deleted");
  });
}

This will delete the post on the Backend and confirm deletion through a console.log message. Subsequently, you can update the local Post Variable accordingly.

For further understanding of Observables and Subscription, visit http://reactivex.io/

Answer №2

It turns out that the root of the issue was actually related to the post ID - a detail that got me off track for a while. The essential part is ensuring that the ID is returned from the node in the add post request, as shown below:

post
    .save()
    .then(addedPost => {
      console.log(addedPost + 'ADD');
      res.status(201).json({
        message: 'Post Added',
        postId: addedPost._id
      });
    })

Following this, the service implementation resembles the following snippet:

.subscribe(responseData => {
        console.log(responseData.message);
        post.id = responseData.postId;
        this.posts.push(post);
        this.postsUpdated.next([...this.posts]);
      });

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

Troubleshooting problems with routing for an Angular 5 single page application when serving it from a Lumen 5.2 controller

I am facing an issue with serving an Angular SPA from a single routed Lumen endpoint. While the initial boot of the Angular application works fine when navigating directly to the endpoint, loading any child route of the Angular SPA does not work properly. ...

Implement foreach in Angular with the help of Concatmap

Issue: I am facing a challenge while attempting to make 3 HTTP post requests to 3 different endpoints using concatMap to sequentially HTTP post to an observable. The problem arises when I try to extract each value from the formarray using a foreach loop. ...

What is the best way to send a list of data as either strings or integers through a REST API using Angular's

While trying to post data from Angular formData to a Django REST API, I encountered an error saying "Incorrect type. Expected pk value, received str." Here is how I am currently sending the data using form data: let noticeData = this.announceForm.value; i ...

Transforming httpClient responses into structured model objects in Angular 6

I am seeking guidance on the usage of Angular 5 httpClient. This particular model class contains a method called foo() that I wish to retrieve from the server export class MyClass implements Deserializable{ id: number; title: string; deserialize(i ...

Tips for identifying MIME type errors in an Angular 9 application and receiving alerts

While working on my Angular app, I encountered the MIME type error Failed to load module script: The server responded with a non-javascript mime type of text/html. Fortunately, I was able to resolve it. Now, I'm stuck trying to figure out how to rece ...

Organize array by "categories" in Javascript and preserve the original sequence

There is a dataset presented below: [ { "name": "Item1", "section": "section1", "total": 3, }, { "name": "Item1", "section": "section2", "total": 4, }{ "name": "Item1", "section": "section3", "total": 7, }, { "name" ...

I encountered an Angular error that is preventing me from updating and uploading images to my Firebase Storage because it is unable to locate the storage bucket

Hey there fellow developers! I'm currently working on a simple Angular app that allows users to upload images to a gallery. However, I've encountered an issue while trying to upload the images to Firebase Storage. I keep getting an error mentioni ...

How to traverse a JSON file using TypeScript within an Angular application?

[ { "title": "Marker 1", "innercontent": "the Porcelain Factory" }, { "title": "Marker 2", "innercontent": "The Taj Mahal " }, { "title": "Marker 3", ...

Make sure to incorporate the .gitignored files that are compiled from typescript when running the `npm install -g

Looking for a way to ignore the JavaScript files compiled from TypeScript in my git repository to make merging, rebasing, and partial commits easier. Here's how I have it set up: tsconfig.json { "compilerOptions": { "outDir": "./dist" ...

Change the name of the interface from the imported type

When working with Google Apps Script, I have implemented the Advanced Calendar Service, originally labeled as "Calendar". However, I have renamed it to "CalendarService". How can I incorporate this name change when utilizing the type definitions for Apps S ...

Determining when it is necessary to loop over a variable

I'm facing a situation where I have two different responses based on whether we need to loop over an object or just display a variable. My attempted solution involved using ng-if else, but unfortunately, it didn't work as expected. This is the ...

After defining the NEXTAUTH_URL and NEXTAUTH_SECRET variables, the getServerSession(authOptions) function in NextJS is returning null

I've been attempting to set up OAuth with the Google provider for my Next.js 13 web application. Unfortunately, I'm encountering an issue where getServerSession(authOptions) is returning null. Despite trying various solutions such as setting NEXT ...

What is the best way to extract a property if it may be undefined?

Can anyone help with this TypeScript error I'm encountering during build time? Any suggestions would be appreciated. Error Message: TypeError: Cannot destructure property 'site' of '(intermediate value)' as it is undefined. export ...

Troubleshooting the creation of migration paths in NestJS with TypeORM

After diligently studying the NestJS and TypeORM documentation, I have reached a point where I need to start generating migrations. While the migration itself is creating the correct queries, it is not being generated in the desired location. Currently, m ...

Issues with code functionality following subscription via a POST request

I'm currently facing an issue with a service that utilizes an HTTP post request to communicate with the database. Unfortunately, when I try to implement this in my .ts file, nothing seems to happen after subscribing to the post. The post itself works ...

Securing Routes in React-Ionic app with Firebase Authentication Context

Currently, I'm in the process of setting up Firebase authentication within a React-Ionic application. I have implemented some protected routes that require authentication to access them. While the setup is partially working, there are still some issue ...

Unable to access FireReader in Ionic 3, while Ionic 4 functions properly

After building my Ionic project on two different computers, I noticed that I received varying results. On the first computer: Ionic Info Ionic: ionic (Ionic CLI) : 4.2.1 (/usr/local/lib/node_modules/ionic) Ionic Framework : ionic-angular 3.9.2 ...

Encountering a Webpack compilation error following the installation of a new package

I am currently working with a boilerplate code for Angular 4 and encountering an issue. Everything was functioning properly until I downloaded a new package from npm. After doing so, I started receiving the following error message and the command ng serve ...

Developing a Typescript module, the dependent module is searching for an import within the local directory but encounters an issue - the module cannot be found and

After creating and publishing a Typescript package, I encountered an issue where the dependent module was not being imported from the expected location. Instead of searching in node_modules, it was looking in the current folder and failing to locate the mo ...

Transforming file location to base64 encoded format using TypeScript

I have the path of an image and need to convert it to base64 format, similar to this data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUg... function encodeImageToBase64(url, callback) { var xhr = new XMLHttpRequest(); xhr.onload = function() { va ...