删除API调用不起作用

时间:2018-04-21 01:43:33

标签: angular api http

即使它在Postman中工作,我似乎无法将我的删除http调用工作。我已经尝试过调试,但这一切似乎都有效,但它仍然存在于我的数据库中。我真的很感激任何帮助,我真的在我的智慧结束。

这是我的HTML

 <tbody *ngFor="let item of todolist">
                    <tr *ngIf="item.state == 'Complete'">
                        <td>{{item.id}}</td>
                        <td>{{item.name}}</td>
                        <td>{{item.description}}</td>
                        <td>{{item.due_Date}}</td>
                        <td>
                            <form *ngIf="item" (ngSubmit)="deleteItem(item.id)">
                                <button type="submit" class="form-control">Delete Item</button>
                            </form>
                        </td>
                    </tr>

                </tbody>

这是我的组件

@Component({
selector: 'completeitems',
templateUrl: './completeitems.component.html',
providers: [ToDoService]
})

export class CompleteItemComponent implements OnInit {
public ID: any;
public name: string;
public description: string;
public duedate: Date;
public tags: string;
public state: string;
public todolist: ToDoList[];

constructor(private activeRoute: ActivatedRoute, private todoService: 
ToDoService, private router: Router) {
}

ngOnInit(): void {
    this.fetchtodoitems();
}

fetchtodoitems(): void {
    this.todoService.getToDoListItems().subscribe(results => this.todolist = 
results);
}


public deleteItem(id: string) {
    this.todoService.deleteItem(id).subscribe();
    window.location.reload();
}

}

这是我的服务:

@Injectable()
export class ToDoService {

constructor(private http: Http) { }

getToDoListItems() {
    return this.http.get('api/todolist')
        .map(response => response.json());
}

getItem(id: any) {
    return this.http.get('api/todolist' + id)
        .map(item => item.json());
}

addToDoListItems(item: ToDoList) {

    return this.http.post('api/todolist', item);
}

deleteItem(id: string) {
    return this.http.delete('api/todolist' + id)
        .map(res => res.json());
}

这是我的API控制器:

[HttpDelete("{id}")]
    public IActionResult Delete(int id)
    {
        try
        {
            var item = this.dbContext.ToDoItems.FirstOrDefault(p => p.ID == 
 id);
            if (item == null)
            {
                return StatusCode(StatusCodes.Status404NotFound);
            }

            this.dbContext.Remove(item);
            this.dbContext.SaveChanges();
            return StatusCode(StatusCodes.Status205ResetContent);
        }
        catch (Exception e)
        {
            return StatusCode(StatusCodes.Status500InternalServerError, 
 e.Message);
        }
    }

1 个答案:

答案 0 :(得分:0)

您在服务中将无效的网址传递给HTTP删除(您应该会在浏览器控制台中看到404)。

您需要在以下位置更改服务中的deleteItem功能:

deleteItem(id: string) {
    return this.http.delete('api/todolist' + id)
        .map(res => res.json());
}

deleteItem(id: string) {
    return this.http.delete('api/todolist/' + id)
        .map(res => res.json());
}
相关问题