Angular2 http delete返回404

时间:2017-10-09 12:20:04

标签: typescript angular-cli

我有一个包含对象的列表,在我的案例中是actor。每个演员都有删除按钮。每当我点击它时,它应该从我的api上的te json文件中删除对象并立即刷新列表,以便不再显示已删除的对象。但是我的删除函数返回404错误,我似乎无法理解为什么。

组件文件:

import { Component, OnInit } from '@angular/core';
import { Actor } from '../../model/actor';
import { ActorService } from '../../service/actor.service';

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


export class ActorListComponent implements OnInit {
  actors: Actor[];
  selectedActor: Actor;
    constructor(private actorService: ActorService) { }

    getActors(): void {
        this.actorService.getActors().then(actors => this.actors = actors);
    }

    ngOnInit(): void {
        this.getActors();
    }
    delete(actor: Actor): void {
        this.actorService
            .delete(actor.id)
            .then(() => {
            this.actors = this.actors.filter(a => a !== actor);
            });
    }
}

html:

<button (click)="delete(actor); $event.stopPropagation()" >
    <fa class="list-btn" [name]="'trash'"></fa>
</button>

和我的服务:

import { Injectable } from '@angular/core';
import { Actor } from '../model/actor';
import {Http, Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class ActorService {
    private headers = new Headers({'Content-Type': 'application/json'});
    private actorsUrl = '/app/persons.json';
    constructor(private http: Http) { }
    getActors(): Promise<Actor[]> {
        return this.http.get(this.actorsUrl)
            .toPromise().then(response => <Actor[]>response.json().personList)
            .catch(this.handleError);
    }
    private handleError(error: any): Promise<any> {
        console.error('Error: ', error);
        return Promise.reject(error.message);
    }
    getActor(id: string): Promise<Actor> {
        return this.getActors()
            .then(actors => actors.find(actor => actor.id === id));
    }
    delete(id: string): Promise<void> {
        const options = new RequestOptions({headers: this.headers});
        const url = `${this.actorsUrl}/${id}`;
        console.log('deleting actor ' + id);
        return this.http.delete(url, options)
            .toPromise()
            .then(() => null)
            .catch(this.handleError);
    }
}

1 个答案:

答案 0 :(得分:1)

您确定要创建正确的网址吗? 404仅在URL不正确时发生。尝试用邮递员发送请求。它总是帮助我。