【发布时间】:2019-09-06 14:19:53
【问题描述】:
我的服务文件,它从 mongoDB 发送/获取数据:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { filter, isEmpty, map } from 'rxjs/operators';
import { Employee } from './employee';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
uri = 'http://localhost:4000/employees';
data: Employee[];
addEmployee(empObj) {
this.http.post(`${this.uri}`, empObj).subscribe(res => { console.log('Done') })
alert('Done adding data');
}
getEmployees(): Observable<Object> {
return this.http.get(`${this.uri}`)
}
getEmployee(id: number): any {
return this.http.get('https://api.myjson.com/bins/mpg19')
}
deleteEmployee(id: number) {
console.log('ID of employee to be deleted', id);
return this.http.get(`${this.uri}/delete/${id}`);
}
}
这是我执行 CRUD 操作的文件。
const express = require('express');
const app = express();
const employeeRoute = express.Router();
let Employees = require('../models/Employee');
employeeRoute.route('/').post(function (req, res) {
console.log('coming here', req.body)
let employee = new Employees(req.body);
console.log('data to save is: ', employee)
employee.save().then(employee => { res.status(200).json({ 'employee': 'Employee added in successfully' }) })
})
employeeRoute.route('/').get(function (req, res) {
console.log('Employees Fetched');
let employees = [];
Employees.find({}, function (err, results) {
if (err) {
console.log(err);
}
else {
employees = results;
res.json(employees);
}
})
})
employeeRoute.route('/delete/:id').get(function (req, res) {
console.log('Delete Function Called')
Employees.findByIdAndRemove({ id: req.params.id }), function (err, Employees) {
console.log('Id against which employee is deleted: ', id);
if (err) res.json(err);
else res.json('Successfully removed');
}
});
module.exports = employeeRoute
我的应用程序正在正确地获取和获取数据,因为我正在按照书面教程进行操作,但我对代码的理解有些困惑。那就是:
我的addEmployee(empObj) 函数(在第一个文件中)如何知道从 CRUD 文件中调用哪个函数。
谢谢提前。
【问题讨论】:
-
阅读更多关于 REST 模式的信息,实践将一目了然
-
我已经用谷歌搜索过了,但仍然感到困惑,这就是为什么在这里发布。如果您有任何用于上述目的的有用资源,请给我一个链接
-
技术上 GET 在这个 url localhost:4000/employees 应该给你一个列表 在这个 url 上的 POST 应该添加一个员工,这就是你的第二个文件的定义。 localhost:4000/employees/:id 上的 GET 应该返回单个员工,localhost:4000/employees/:id 上的 PATCH 或 PUT 应该更新员工的详细信息,localhost:4000/employees/:Id 上的 DELETE 应该从数据库中删除员工在您的情况下,您正在为 GET 请求选择 DELETE 的自定义路由这太可怕了。希望这是有道理的
-
是的,我的删除功能不起作用。即使我现在使用
deletehttp 方法,我应该怎么做才能使其工作 -
错误是什么?
标签: node.js angular mongodb express