将JSON值映射到Angular 4中的UI字段
我正在尝试使用带有Angular 4的Mean Stack进行更新操作。我是这项技术的新手。对于更新oprtn,我需要根据选择的id将值映射到UI表单以更新记录。我的数据服务是以JSON的形式从MongoDb数据库获取记录值,需要更新。但是,我无法将这些参数设置为typescript代码中表单上的字段。
我正在使用JSON.parse方法来实现它但是得到以下错误。
错误:SyntaxError:JSON.parse()中位置0的JSON中出现意外的标记u
打字稿代码
updateitem(itemid){
let updatedresult;
console.log("toupdateid", itemid);
this.dataService.getItemById(itemid)
.subscribe(
res=> {
this.res =JSON.parse(res);
this.newSession.trainingName =res["TrainingName"],
this.newSession.description = res["Description"];
console.log('newsession', this.newSession);
},
err=> this.apiError = err,
() => {
this.getFormdetails();
}
)
}
DataService的
getItemById(id):Observable<any>{
console.log('idvalue', id);
return this.http.get("http://localhost:3000/getitem"+"/"+ id)
.map(result =>{ this.result = result.json();
console.log('getitembyid' ,result.json())})
.catch((error:any) => Observable.throw('Server Error to get the item'));
}
}
回答如下:
.map(result =>{ this.result = result.json();
console.log('getitembyid' ,result.json())})
将其更改为
.map(result => result.json())
并删除ts代码中的JSON.parse,因为它现在将作为JSON对象从服务返回