簡體   English   中英

Angular Put 方法不更新數據

[英]Angular Put Method not updating data

我是 MEAN 堆棧的新手,在使用 put 方法更新數據時遇到問題,我已經使用 postman 進行了測試,它工作正常,但是當我在 angular 上使用它時它不起作用。 沒有出現任何錯誤,這是我在更新數據后在控制台中得到的 [is give success update][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,仍然不知道如何解決此錯誤

我想分享我用平均堆棧更新數據的方式。 它與您的代碼略有不同,但它可以工作並且經過了開玩笑的測試。 我想分享我更新用戶資料的例子

我在我的后端 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 model 具有相同屬性的用戶類

// 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);
  }

然后我可以從我想更新我的用戶的組件中調用服務 function

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

我希望我的代碼片段能夠幫助到你。 如果還有什么需要澄清的,請告訴我:對不起,如果這不是最完美的答案,因為這是我對 SO 的第一個答案之一 :)

401 表示身份驗證錯誤。

發帖有效嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM