arrays - 如何将值从数组分配给模型
问题描述
我从数组分配到模型有问题。我想从 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>
解决方案
我不知道您的数据库结构是什么样的,但可以说它与您的前端相同...
- 首先我不确定你为什么
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)
});
推荐阅读
- javascript - 使用 cypress 连接 SQL 数据库
- php - 从控制器获取数据到列数据表(Codeigniter)
- html - 在手机屏幕上创建响应式圆弧
- hyperledger-fabric - 在超级账本结构中建立自定义网络时出错
- python - 捕获和存储对象检测
- cassandra - Cassandra 如何被认为是存储非结构化数据的优秀数据库?
- reactjs - pivotUtilities Unfedined
- delphi - 尝试在类型库中创建父级 VCL TFrame 时出现 EInvalidOperation 异常
- java - 为什么我的代码没有按预期工作?我认为空指针异常存在问题。(爪哇)
- r - 在 R 中创建条件变量