首页 > 解决方案 > 如何将值从数组分配给模型

问题描述

我从数组分配到模型有问题。我想从 userFromDb 分配 firstName 值并将此值分配给模型中的 firstName ,并且与其他值相同。我不知道该怎么做:(

用户

export interface User{

id:string;
firstName:string;
lastName:string;
email:string;
password:string;
}

更新用户组件.ts

userFromDb: Array<Object>;

model:User = {
id: '',
firstName: '',
lastName: '',
email: '',
password: ''}

ngOnInit() {

let id = this.route.snapshot.paramMap.get('id');

this.userService.getUser(id).subscribe(result => {
  console.log(result)
  this.userFromDb = result
  console.log(this.userFromDb)
});

更新用户组件.html

<div>
    <form action="" #f="ngForm" (ngSubmit)="saveUser()" novalidate>
        <div>
            <label for="firstName">First Name: </label>
            <input [(ngModel)]="model.firstName" type="text" id="firstName" name="firstName" placeholder="Name">
        </div>
        <div>
            <label for="lastName">Last Name: </label>
            <input [(ngModel)]="model.lastName" type="text" id="lastName" name="lastName" placeholder="Name" >
        </div>
        <div>
            <label for="email">Email: </label>
            <input [(ngModel)]="model.email" type="text" id="email" name="email" placeholder="Name" >
        </div>
        <div>
            <label for="password">Password: </label>
            <input [(ngModel)]="model.password" type="text" id="password" name="password" placeholder="Name" >
        </div>
        <button type="submit">Submit</button>
    </form>
</div>

标签: arraysangularngmodel

解决方案


我不知道您的数据库结构是什么样的,但可以说它与您的前端相同...

  • 首先我不确定你为什么userFromDb是一个数组,它会返回多个用户吗?

如果您只想插入值,那么最简单的方法是:

this.userService.getUser(id).subscribe(result => {
  console.log(result)
  this.userFromDb = result
  this.model.firstName = this.userFromDB[0].firstName
  // same with other values here
  console.log(this.userFromDb)
});

推荐阅读