mongoose 我的数据只在我在angular和mongodb中使用CRUD操作时才在前端更改,刷新后它再次被设置为默认值

wgxvkvu9  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(137)

刷新页面后,我的数据将切换为默认值,并且由于我使用的是Rest API,mongoDB中的值不会发生变化。

以下是我在Rest API中用于更新数据的后端代码。

router.put('/:id',(req,res)=>{
  if(!ObjectId.isValid(req.params.id))
     return res.status(400).send(`No record with given id:${req.params.id}`)

     let emp = {
     firstName: req.body.firstName,
     lastName: req.body.lastName,
     relationship: req.body.relationship,
     dob:req.body.dob,
     ssn:req.body.ssn,
     memberid:req.body.memberid,
     status:req.body.status,
     };

     Employee.findByIdAndUpdate(req.params.id,{$set:emp},{new :true},(err,doc)=>{
       if(!err){
          res.send(doc);
       }
       else{
          console.log('error in Employee update:' +JSON.stringify(err,undefined,2))
       }
     })
})
module. Exports = router;

以下是服务文件的后端代码。

export class UsersDataService {
  selectedEmployee: Employee;
  statusChanged:any='';
  userSel:any={};
  searchResult:any='';
  userObj:any=[];
  baseURL ='http://localhost:8000/employees/'
  constructor(private http:HttpClient) { 
  }

  users(){
     this.http.get(this.baseURL).subscribe((res) => {
      this.userObj = res ;
     })
  }

  updateUser(user:any){
    console.log(user);
    this.http.put(this.baseURL + user._id,user).subscribe((data) => {
      console.log(data);
    })
  }
}

以下是HTML组件的代码

<td><button type="button" class="btn btn-success btn-sm bb"(click)="enrollUser(user)"> Enroll</button> </td>

下面是组件ts文件的代码

enroll = false;
userSelected:any={};
unEnroll = false;
unenrolluser ='active';

constructor(public usersData:UsersDataService) {
}

 enrollUser(data:any){
      console.log(data);
      data.status = this.unenrolluser;
      this.userSelected = data;

    
      this.enroll = true;
      this.usersData.updateUser(this.userSelected)

  }

我希望一旦我点击注册按钮,状态将在前端和后端都更改为活动。意味着数据库中的数据也将更新,在我的情况下,休息API也应该得到更新。

aiazj4mn

aiazj4mn1#

在服务文件中返回请求响应:

updateUser(user:any){
    console.log(user);
    return this.http.put(this.baseURL + user._id,user);
    }

然后订阅组件并更新实体:

enrollUser(data:any){
      console.log(data);
      data.status = this.unenrolluser;
      this.userSelected = data;
      this.enroll = true;
      this.usersData.updateUser(this.userSelected).subscribe(res => 
      this.userSelected = res);
      }

希望它对你有用。

相关问题