首页 > 解决方案 > 无法在角度 8 中获取编辑表单组件中的数据

问题描述

我无法获取表单中的数据来编辑和更新它。当我单击编辑按钮时,它会将我带到编辑用户组件,我的 API 工作正常,但唯一的问题是数据没有提取到表单中。这是我的代码...

用户组件 Html 代码

<table class="table">
        <thead class="thead-dark">
          <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
            <th colspan="2">Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let user of users">
            <td>{{ user.name }}</td>
            <td>{{ user.email }}</td>
            <td>{{ user.phone }}</td>
            <td>
              <a
                [routerLink]="['/edit', user._id]"
                class="btn btn-primary"
                (click)="onEdit(user._id)"
                >Edit</a
              >
            </td>
            <td>
              <a
                [routerLink]=""
                class="btn btn-danger"
                (click)="onDelete(user._id)"
                >Delete</a
              >
            </td>
          </tr>
        </tbody>
      </table>

用户组件 ts 代码

export class UserComponent implements OnInit {
  users: ShowUser[];
  editUser: ShowUser;
  user: User;
  constructor(private userService: UserService, private router: Router) {}

  ngOnInit() {
    this.userService.showUsers().subscribe((data: ShowUser[]) => {
      this.users = data;
    });
  }

  userModel = new User('', '', '', '', '');

  onSubmit() {
    this.userService.addUser(this.userModel).subscribe(data => {
      console.log('Success!', data);
      this.ngOnInit();
    });
  }

  onEdit(id: String) {
    this.userService.editUser(id).subscribe(res => {
      this.editUser = res;
      console.log(res);
      this.router.navigate(['edit', id]);
    });
  }

  onDelete(id: String) {
    this.userService.deleteUser(id).subscribe(res => {
      this.user = res;
      this.ngOnInit();
      console.log(res);
    });
  }
}

显示用户界面

export interface ShowUser {
  id: String;
  name: String;
  email: String;
  phone: String;
}

用户模型

export class User {
  constructor(
    public name: string,
    public email: string,
    public phone: string,
    public password: string,
    public passwordConfirm: string
  ){}
}

用户服务

export class UserService {
  user: User;
  showUser: ShowUser;
  url = 'http://localhost:5000/api/users';

  constructor(private http: HttpClient) {}

  addUser(user: User) {
    return this.http.post<any>(`${this.url}`, user);
  }

  showUsers() {
    return this.http.get(this.url);
  }

  editUser(id: String) {
    return this.http.get<ShowUser>(`${this.url}/edit/${id}`);
  }

  updateUser(user: User, id) {
    return this.http.post(`${this.url}/update/${id}`, user);
  }

  deleteUser(id: String) {
    return this.http.delete<User>(`${this.url}/delete/${id}`);
  }
}

编辑用户组件 Html

<div class="container">
  <div class="row justify-content-center">
    <div class="col-md-5">
      <h1 class="text-center">Edit User</h1>
      <form #user="ngForm">
        <div class="form-group">
          <label for="name">Name</label>
          <input
            type="text"
            class="form-control"
            id="name"
            name="name"
            [(ngModel)]="user.name"
            placeholder="Enter Name"
          />
        </div>
        <div class="form-group">
          <label for="email">Email</label>
          <input
            type="email"
            class="form-control"
            id="email"
            name="email"
            [(ngModel)]="user.email"
            aria-describedby="emailHelp"
            placeholder="Enter email"
          />
          <small id="emailHelp" class="form-text text-muted"
            >We'll never share your email with anyone else.</small
          >
        </div>
        <div class="form-group">
          <label for="phone">Phone</label>
          <input
            type="text"
            class="form-control"
            id="phone"
            name="phone"
            [(ngModel)]="user.phone"
            placeholder="Enter Phone Number"
          />
        </div>
        <button
          type="button"
          class="btn btn-primary btn-block"
          (click)="updateUser(user)"
        >
          Update
        </button>
      </form>
    </div>
  </div>
</div>

编辑用户组件 ts 代码

export class EditUserComponent implements OnInit {
  user: any = {};

  constructor(
    private userService: UserService,
    private activatedRoute: ActivatedRoute,
    private router: Router
  ) {}

  ngOnInit() {
    this.activatedRoute.params.subscribe(params => {
      this.userService.editUser(params['id']).subscribe(res => {
        this.user = res;
      });
    });
  }

  updateUser(updatedUser: User) {
    console.log('Updated', updatedUser);
    this.activatedRoute.params.subscribe(params => {
      this.userService.updateUser(params['id'], updatedUser);
    });
    this.ngOnInit();
    this.router.navigate(['']);
  }
}

控制器

exports.editUser = async (req, res) => {
  try {
    const user = await User.findById(req.params.id);
    res.status(200).send(user);
  } catch (error) {
    res.status(404).send(error);
  }
};

exports.updateUser = async (req, res) => {
  try {
    const updatedUser = await User.findByIdAndUpdate(req.params.id, req.body, {
      new: true
    });
    res.status(200).json({
      status: 'successfully updated',
      data: {
        updatedUser
      }
    });
  } catch (error) {
    res.status(400).send(error);
  }
};

蜜蜂

router.get('/edit/:id', editUser);
router.post('/update/:id', updateUser);

标签: javascriptangular

解决方案


推荐阅读