2

I have a list of posts in my component that I retreive by using this code:

export class PostsComponent implements OnInit
{
    posts;

    constructor(private http: Http) { }

    ngOnInit: void()
    {
        this.http.get('/posts').map(res => res.json()).subscribe(res => this.posts = res);
    }

    delete(post)
    {
        this.http.post('/posts/delete'+ post.id)
            .subscribe(res =>
            {
                // delete post from posts, but how?
            });
    }
}

Now my question is how do I remove the post object from the array? Example of the array:

[
    {
        id: 1,
        title: 'Test'
    },
    {
        id: 2,
        title: 'Test'
    },
    {
        id: 3,
        title: 'Test'
    },
]

So I want to remove the post with id 2 from the array, so angular can update my display table. How would I do this?

2 Answers 2

1

If post is an actual element of the array (and not a cloned copy or something), then you could just do

this.posts = this.posts.splice(this.posts.indexOf(post), 1);
Sign up to request clarification or add additional context in comments.

6 Comments

You cannot find object inside array with indexOf. You can only use indexOf() if you are trying to find string in array or string in string
At least in Chrome it works. I am not entirely sure about all the other browsers out in the wild
This is not an example of an actual element of the array but rather you create a new object resembling one of the objects of the array (which is not the same object)
I won't ... why should I? I think you didn't get it
|
1

You just need to loop through the list of posts and remove the one you want:

delete(post)
{
    this.http.post('/posts/delete'+ post.id)
         .subscribe(res =>
         {
              for(let p in this.posts) {
                   if(this.posts[p].id == post.id) {
                        this.posts.splice(p, 1);
                        break;
                   }
              }
         });
}

Or there is solution to use .filter():

delete(post)
{
    this.http.post('/posts/delete'+ post.id)
        .subscribe(res =>
         {

             this.posts = this.posts.filter(item => {
                  return item.id != post.id;
             })
        });
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.