Wednesday, 10 May 2017

Angular 4 DELETE function not working (MEAN stack)

I'm trying a small CRUD app, whose get, post, put requests are working all fine.. but i'm not sure why the delete function is not working. I used Mlab for my mongodb, and mongojs to make the connection.

I don't see any errors, and i get a 200 response code when i click the delete button.enter image description here

Here is the front-end -

<td><input (click)="deleteCandidate(candidate)" type="button" class="btn btn-danger pull-right" value="Delete"></td>

The function in my component -

deleteCandidate(candidate){
  var candidates = this.candidates;

  this._candidateService.removeCandidate(candidate._id)
  .map(res => res.json())
  .subscribe(data => {
    if(data.n == 1){
      for(var i = 0; i < candidates.length; i++){
        if(candidates[i]._id = candidate._id){
          candidates.splice(i, 1);
        }
      }
    }
  });
}

And the corresponding service -

removeCandidate(id)
    {
        return this._http.delete('/api/v1/candidate/'+id);  
    }

And here is the route for ExpressJS (i've used mongojs) -

// Delete a candidate
router.delete('/candidate/:id', function(req, res, next) {
    db.candidates.remove({
        _id: mongojs.ObjectId(req.param.id)
    }, '', function(err, result) {
            if(err){
            res.send(err);
        }
        else {
            res.json(result);
        }
    });
});

Your help is appreciated, thanks!



via codemode

No comments:

Post a Comment