首页 > 解决方案 > 为什么 GET 工作,但 DELETE 和 POST 在 Angular 2 中不起作用(错误:404)?

问题描述

实际上我的http工作,get工作,但delete没有post工作。你觉得我会怎么做?

这是我的组件,我不知道为什么它不起作用

组件.ts

import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
import { HttpService } from '../http.service';

@Component({
      selector: 'app-http',
      templateUrl: './http.component.html',
      styleUrls: ['./http.component.css']
})

export class HttpComponent implements OnInit {

      followers = [];
      constructor(private hService: HttpService,
        private http: Http
      ) { }

      private url: string = "./app/http/followers.json";


      ngOnInit() {
        this.http.get(this.url)
          .map((response: Response) => response.json())
          .subscribe(user=>this.followers=user)

      }

      createpost(input: HTMLInputElement) {
        let name = { name: input.value };
        input.value = '';

        this.http.post(this.url, JSON.stringify("name"))
          .subscribe(response => {
            name = response.json();
            this.followers.splice(0, 0, name);
          });
      }
      deletepost() {
        this.http.delete(this.url + '/' + "id")
          .subscribe(response => {
            let index = this.followers.indexOf("id");
            this.followers.splice(index, 1);
          });

      }


    }

这是我的 http>follower.json

示例数据

组件.html

<div>

  <h2>Followers list</h2>
  <input type="text" #name (keyup.enter)="createpost(name)" class="list-control">
  <button class="btn btn-primary" (click)="createpost(name)">Add to fallowers</button>


  <ul class="list-group">
    <li *ngFor="let follower of followers" class="list-group-item">
      <button class="btn btn-danger" (click)="deletepost(name)">UnFollow</button>
      {{follower.name}} 

    </li>
  </ul>
</div>

标签: angularposthttp-delete

解决方案


推荐阅读