【发布时间】:2021-04-29 11:21:59
【问题描述】:
我在更新列出的表单时遇到错误,ReactForm 这是我附加的代码请帮我解决这个问题...提前致谢 我的代码::
import { CommonService } from './../common.service';
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-update-resturant',
templateUrl: './update-resturant.component.html',
styleUrls: ['./update-resturant.component.css']
})
export class UpdateResturantComponent implements OnInit {
alert : Boolean = false;
updateResto = new FormGroup({
Name: new FormControl(''),
Email: new FormControl('')
})
constructor(private resto:CommonService, private router: ActivatedRoute) { }
ngOnInit(): void {
this.resto.getCurrentData(this.router.snapshot.params.id).subscribe((result)=> {
console.log(result)
this.updateResto = new FormGroup({
Name: new FormControl(result['Name']),
Email: new FormControl(result['Email'])
})
}
}
错误::
元素隐式具有“任何”类型,因为“电子邮件”类型的表达式不能用于索引类型“对象”。 “对象”类型上不存在属性“电子邮件”。
服务代码::
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class CommonService {
URL= "http://localhost:3000/list"
constructor(private _http:HttpClient) { }
getRestoList(){
return this._http.get(this.URL)
}
addResto(data: any){
return this._http.post(this.URL, data);
}
// deleteCurrentData(id: any){
// return this._http.delete(`${this.URL}/${id}`)
// }
getCurrentData(id: number){
return this._http.get(`${this.URL}/${id}`)
}
}
【问题讨论】:
-
您应该只更新
this.updateRestoelems 值,而是重新创建它们。 -
检查以下Plunker
-
通过将我的代码更新为您提到的代码,正在编译 IT,但没有将后端值放入表单,它只是在栏上显示 Oject 对象 ngOnInit(): void { this.resto .getCurrentData(this.router.snapshot.params.id).subscribe((result)=> { console.log(result) this.updateResto.controls['Name'].setValue(result), this.updateResto.controls[ '电子邮件'].setValue(result) }) }
标签: angular