首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在angular7中删除项目

在angular7中删除项目
EN

Stack Overflow用户
提问于 2019-08-27 23:17:42
回答 1查看 144关注 0票数 0

我想从机器列表中删除一台机器,在后端,它工作正常。但是当我尝试使用Angular删除它时,我在控制台上得到了一个错误:

代码语言:javascript
复制
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown 
Error", url: "http://localhost:3001/machines/delete", ok: false, …}
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, 
total: 0, type: "error", …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: 
Map(0)}
message: "Http failure response for http://localhost:3001/machines/delete: 
0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: "http://localhost:3001/machines/delete"

那是我的file.html

代码语言:javascript
复制
 <button type="button"  (click)="delete(machine.id)"  (click)="showNotificationI('top','left',machine.id)" class="btn btn-danger" >Delete</button>

我的file.component.ts:

代码语言:javascript
复制
delete(id) {
this.machinesService.deleteMachine(id).subscribe();}

我的文件machines.service:

代码语言:javascript
复制
  deleteMachine(id): Observable<any>

{

代码语言:javascript
复制
    let myHeaders: HttpHeaders = new HttpHeaders();
    myHeaders = myHeaders.append('Authorization', 'Basic YWxpOmFsaQ==');
    return this.http.post(`${environment.apiUrl}/machines/delete`,id, { headers: myHeaders, withCredentials: true });}

对于后端,我使用node js,我的代码是:

代码语言:javascript
复制
router.post('/delete', function (req, res) {
Machine.deletemachine(req.body, function (err, count) {
    if (err) {
        res.status(400).json(err);
    }
    else {
        res.json(req.body);
    }
});});

我错过了什么?

EN

回答 1

Stack Overflow用户

发布于 2019-08-27 23:55:59

假设你有一个名为listMachines的数组,它包含了所有的机器对象,你可以这样做:

代码语言:javascript
复制
delete(id) {
    this.machinesService.deleteMachine(id).subscribe((res) => {
        let indexToFind = null;

        this.listMachines.forEach((machine, index) => {
            if(machine.id === id) {
                indexToFind = index;
                return;
            }
        });

        if(indexToFind) {
            this.listMachines.splice(indexToFind, 1);
        }
    })
}

甚至更好

代码语言:javascript
复制
delete(id) {
    this.machinesService.deleteMachine(id).subscribe((res) => {
        this.listMachines = this.listMachines.filter((machine) => machine.id !== id);
    });
}

删除你的对象后端不会在前端删除它,一旦后端完成了他的工作,你就需要手动删除它

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57677832

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档