Angular 5 http delete not working

2020-04-16 18:43发布

问题:

I'm trying to delete an article using http.delete but Angular isn't making the request. I'm not sure what's missing.

blog-service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';
const BASE_URL = 'http://localhost:8080';

[...]

deleteArticle(id) {
    this.http.delete(`${BASE_URL}`+'/api/articles/'+ id)
}

edit-blog.component.ts:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from "@angular/router";
import { BlogService } from "../../../services/blog.service";

[...]

onPostDelete() {
    this.blogService.deleteArticle(this.urlParam.id)
}

ngOnInit() {
    this.urlParam = this.activatedRoute.snapshot.params;

    this.blogService.getArticle(this.urlParam.id)
    .subscribe(data =>this.article = data);
}

edit-blog.component.html:

<form [formGroup]="createPostForm" (submit)="onPostSubmit()" autocomplete="off">
[...]
</form>

<button class="btn btn-outline-danger" (click)="onPostDelete()">Delete Post</button>

Could somebody tell me what's missing? thanks

回答1:

Inorder to make the request, you need to subscribe as follows

onPostDelete() {
   this.blogService.deleteArticle(this.urlParam.id).subscribe((response) => {
     console.log("deleted"));
   });
}

and modify your blog-services as follows,

deleteArticle(id) {
   return this.http.delete(`${BASE_URL}`+'/api/articles/'+ id).map((response: Response) => response.json())
}


标签: angular