Node-Mongo / Angular:关于插入数据的问题

时间:2019-06-10 15:17:59

标签: post mean-stack

我正在遵循此MEAN堆栈教程,但是在使用表单提交数据时遇到了麻烦。我可以读取值,因此get请求有效,但该帖子似乎不起作用,尽管我可以将提交的数据记录在Angular服务中。代码:

HTML

<form (ngSubmit)="addUser()">
      <input class="form-control" [(ngModel)]="user.name" name="name">
      <input type="submit" class="btn btn-danger">
      </form>

  <ul *ngFor="let user of users">
        <li>{{user.name}}</li>
      </ul>

TS:

users: Users[];
  user: Users = {
    id: null,
    name: null

  };
  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.getUsers();
  }

getUsers() {
  this.dataService.getUsers().subscribe(data=> {
    this.users = data as unknown as Users[];
    console.log(data);
  });
}

addUser() {
  this.dataService.addUser(this.user);
}

服务:

getUsers(): Observable<Users> {
  return this.http.get<Users>(this.baseURL);
}

addUser(user: Users){
  console.log(user);
  return this.http.post(this.baseURL, user, {
    headers: new HttpHeaders({
      'Content-Type': 'aplication/json'
      })
    });
  }

BackENd上的post方法:

router.post('/', (req, res) => {
    var emp = new Employee({
        name: req.body.name,

    });
    emp.save((err, doc) => {
        if (!err) { res.send(doc); }
        else { console.log('Error in Employee Save :' + JSON.stringify(err, undefined, 2)); }
    });
});

0 个答案:

没有答案