【问题标题】:Angular Put Method not updating dataAngular Put 方法不更新数据
【发布时间】:2020-11-16 13:38:45
【问题描述】:

我是 MEAN 堆栈的新手,在使用 put 方法更新数据时遇到问题,我已经使用邮递员进行了测试,它工作正常,但是当我在 Angular 上使用它时它不起作用。没有出现任何错误,这是我在更新数据后在控制台中得到的 [提供成功更新][1] 但我更新的数据没有任何变化。我对创建和删除方法没有问题,只是更新有问题的方法

这是我的代码

更新服务

  updateData(id, data): Observable<any>{
let url = `${this.baseUri}/update/${id}`;
return this.http.put(url,data, { headers : this.headers }).pipe(
  catchError(this.errorManagement)
)}

更新组件

OnSubmit(id){
  let record = this.updateForm.value
  if(!record){
     this.notif.showError('can\'t do update data','Update data Error')
     return false;
}else{
    return this.motorService.updateData(id, record).subscribe(res=>{
    console.log(record)
  },(error) => {
    console.log(error)
  });
}}}

更新路线

listDataRoute.route('/update/:id').put((req,res,next)=>{
    listData.findByIdAndUpdate(req.params.id,{
        $set : req.body
    },{new: true, useFindAndModify: false},(error, data)=>{
         if (data.n > 0) {
        res.status(200).json({
          message: 'profile updated'
        });
      } else {
        res.status(401).json({
          message: 'not authorized'
        });
      }
    })
    .catch(error => {
      res.status(500).json({
        message: 'updating profile failed'
      });
    })
})

知道我做错了什么吗?我已经被这个错误困住了 5 个小时,谢谢 [1]:https://i.stack.imgur.com/ryR8g.png

更新:在“更新路由”中添加一些代码后出现错误 401,仍然不知道如何解决此错误

【问题讨论】:

  • 您是否比较过您是否缺少要更新的对象的任何属性。当我遇到与您相同的问题时,我的后端控制器功能中缺少一些属性
  • 感谢您的评论,您能解释一下缺少哪些属性吗?我很困惑@Fiehra
  • 我正在发送一个更新,例如我更新了我的年龄。但我的后端控制器没有处理年龄属性。所以这就是更新成功但我的年龄从未改变的原因。我发布了我如何处理更新调用的代码希望它有所帮助:)

标签: node.js angular mongodb typescript mean-stack


【解决方案1】:

id 喜欢分享我用平均堆栈更新数据的方式。它与您的代码略有不同,但它可以工作并且经过了开玩笑的测试。我想分享我更新用户资料的例子

我在我的后端 user.js 中创建了一个 userModel

// user.js
const mongoose = require("mongoose");
const uniqueValidator = require("mongoose-unique-validator");
mongoose.set('useCreateIndex', true);

const userSchema = mongoose.Schema({
    id: String,
    email: { type: String, unique: true },
    username: { type: String, unique: true },
    password: { type: String, required: true },
    currentLocation: String,
    age: String,
  });

  userSchema.plugin(uniqueValidator);
 
  module.exports = mongoose.model('User', userSchema);

然后我在 profileController.js 中编写更新方法

// profileController.js
exports.update = (req, res, next) => {
  const user = new User({
    _id: req.body.id,
    email: req.body.email,
    username: req.body.username,
    currentLocation: req.body.currentLocation,
    age: req.body.age,
  });
  User.updateOne({ _id: req.params.id }, user).then(result => {
      if (result.n > 0) {
        res.status(200).json({
          message: 'profile updated'
        });
      } else {
        res.status(401).json({
          message: 'not authorized'
        });
      }
    })
    .catch(error => {
      res.status(500).json({
        message: 'updating profile failed'
      });
    });
}

在我的 profilerService.ts(前端)中,我还使用与后端中的 user.js 模型相同的属性定义了我的用户类

// profile.service.ts
export class User {
  id: string;
  email: string;
  username: string;
  password: string;
  currentLocation: string;
  age: string;

  constructor() {
    this.id = '';
    this.email = '';
    this.username = '';
    this.password = '';
    this.currentLocation = '';
    this.age = '';
  }
}

我还将更新服务调用添加到我的服务文件中

// profile.service.ts
updateProfile(user: User, userId: string) {
    return this.http.put(environment.backendUrl + '/api/user/' + userId, user);
  }

然后我可以从我想要更新我的用户的组件中调用服务函数

  // profile-page.component.ts
  updateProfile(user: User) {
    this.profileService.updateProfile(user, user.id).subscribe(response => {
      console.log('update successfull');
    });
  }

希望我的代码 sn-ps 能够帮助到你!如果还有什么需要澄清的,请告诉我。对不起,如果这不是最完美的答案,因为这是我对 SO 的第一个答案之一 :)

【讨论】:

  • 在我尝试了你的代码后,特别是在 profileController.js 中,我得到了 401 错误,你对这个错误有什么建议吗?谢谢
  • 你确定你传入了正确的id吗? 401 看起来像 User.updateOne({ _id: req.params.id }, user).then 函数不成功。您还可以检查您的网址是否正确以及是否与后端网址匹配
  • 我只是用邮递员检查了我的更新网址,它正在工作,仍然不知道我做错了什么
【解决方案2】:

401 表示身份验证错误。

发帖有效吗?

【讨论】:

  • 谢谢回答,我的应用程序没有使用任何登录用户或身份验证,这就是为什么我不知道如何解决这个错误,你有什么建议吗?
  • 您能检查一下您的浏览器控制台,是否有任何 CORS 错误?另外,你能检查一下 Mongoose 是否成功连接到 Mongo DB?看来猫鼬失败了。
  • 除了 401 错误,我没有收到任何错误,而且我与 mongodb 的连接工作正常,您有什么线索吗? @Rajdeep Debnath
  • 你得到 401 而没有别的,因为在 node.js 方面你只设置了那么多。你能在 Node.js 服务器端同时使用 console.log(data) 和 console.log(error) 吗?
猜你喜欢
  • 2022-07-17
  • 1970-01-01
  • 2019-04-25
  • 2016-10-12
  • 1970-01-01
  • 2014-05-27
  • 2013-11-16
  • 2022-06-25
  • 1970-01-01
相关资源
最近更新 更多