当我在程序中按下“删除”按钮时,当它试图读取数据库以删除记录时出现error。当我切换到Chrome开发者工具中的“网络”标签时,服务器状态为“失败”。我如何才能使此错误消失,并使我的程序从MongoDB的数据库中正确删除内容?
我试图从/responses/
中删除/responses/:id
,但这只会产生相同的结果。
这是我的代码在组件中的样子:
import { Component, OnInit } from '@angular/core';
import { Response } from '../response.model';
import { ResponseService } from '../response.service';
import { ActivatedRoute, Router, Params } from '@angular/router';
@Component({
selector: 'app-response-detail',
templateUrl: './response-detail.component.html',
styleUrls: ['./response-detail.component.css']
})
export class ResponseDetailComponent implements OnInit {
response: Response;
id: string;
constructor(private responseService: ResponseService,
private route: ActivatedRoute,
private router: Router){ }
ngOnInit() {
this.route.params.subscribe(
(params: Params) => {
this.id = params['id'];
this.response = this.responseService.getResponse(this.id);
}
);
}
onEditResponse() {
this.router.navigate(['edit'], {relativeTo: this.route});
}
onDelete(responseId:string){
this.responseService.deleteResponse(responseId);
}
}
这是我的服务(这只是精简版):
import { Injectable, EventEmitter } from '@angular/core';
import { Subject } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Response } from './response.model';
@Injectable({
providedIn: 'root'
})
export class ResponseService {
responseSelectedEvent = new EventEmitter<Response>();
responseListChangedEvent = new Subject<Response[]>();
private responsesUpdated = new Subject<Response[]>();
maxResponseId: number;
responses: Response[] = [];
id: string;
constructor(private http: HttpClient ) {
this.maxResponseId = this.getMaxId();
}
deleteResponse(responseId: string) {
this.http.delete("http://localhost:3000/response/" + responseId)
.subscribe(() => {
const updatedResponses = this.responses.filter(response => response.id !== responseId);
this.responses = updatedResponses;
this.responsesUpdated.next([...this.responses]);
});
}
然后这是我的js文件。
router.delete("/responses/:id", (req, res, next)=>{
Response.deleteOne({ _id: req.params.id }).then(result => {
console.log(result);
res.status(200).json({ message: "Response deleted!"});
});
});
预期的输出应该是当您按下删除按钮时,将从数据库中删除记录。但是,我得到的回报是http://localhost:3000/responses/undefined
。