简体   繁体   中英

Angular Put Method not updating data

i'm newbie with MEAN stack and i have problem when updating data with put Method, i have tested using postman and it works fine, but when i use it on angular its not working. nothing error appear, this what i got in console after updating data [is give success update][1] but nothing change on data that i updated. i don't have problem with create and delete method, just update method that had problem

here's my code

update.service

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

update.component

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

update route

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

any idea what i do wrong? i'm already stuck like 5 hours with this error, thank you [1]: https://i.stack.imgur.com/ryR8g.png

update: i got error 401 after adding some code in "update route", still don't know how to solve this error

id like to share my way of updating data with the mean stack. its a lil different from your code but it works and is tested with jest. id like to share my example with updating a userprofile

i create a userModel in my backend user.js

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

then i write the update method in my 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'
      });
    });
}

in my profilerService.ts (frontend) i also define my userclass with the same properties as the user.js model in my backend

// 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 = '';
  }
}

i also add the update service call into my service file

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

then i can call the service function from my component where i want to update my user

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

i hope my code snippets are able to help you. let me know if anything still needs some clarification: sry if this isnt the most perfect answer as this is one of my first answers on SO :)

401 means Authentication error.

Is post working?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM