Node.js 将JSON值映射到Angular 4中的UI字段
我正在尝试使用角度为4的平均堆栈进行更新操作。我不熟悉这项技术。对于update oprtn,我需要根据更新记录所选的id将值映射到UI表单。我的数据服务以JSON的形式从MongoDb数据库获取记录值,需要更新。但是,我无法将这些参数设置为typescript代码中表单上的字段 我正在使用JSON.parse方法来实现它,但出现以下错误 错误:SyntaxError:JSON中位于JSON.parse()位置0处的意外标记u 打字脚本代码Node.js 将JSON值映射到Angular 4中的UI字段,node.js,mongodb,angular,mean-stack,Node.js,Mongodb,Angular,Mean Stack,我正在尝试使用角度为4的平均堆栈进行更新操作。我不熟悉这项技术。对于update oprtn,我需要根据更新记录所选的id将值映射到UI表单。我的数据服务以JSON的形式从MongoDb数据库获取记录值,需要更新。但是,我无法将这些参数设置为typescript代码中表单上的字段 我正在使用JSON.parse方法来实现它,但出现以下错误 错误:SyntaxError:JSON中位于JSON.parse()位置0处的意外标记u 打字脚本代码 updateitem(itemid){ let
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();
}
)
}
数据服务
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'));
}
}
getItemById(id):可观察{
console.log('idvalue',id);
返回此.http.get(“http://localhost:3000/getitem“+”/“+id”)
.map(result=>{this.result=result.json();
log('getitembyid',result.json())})
.catch((error:any)=>Observable.throw('Server error to get the item');
}
}
换成
.map(result => result.json())
并删除ts代码中的JSON.parse,因为现在它将作为JSON对象本身从服务返回,当服务器发送无效的JSON时会发生此错误。您需要检查服务器的响应 这有不同的原因,但很可能是: 您正在将请求发送到错误的端点。因此,您得到的不是json,而是一个以u开头的文档,它试图解析它。 另一个问题是服务器向您发送了一个错误的响应,该响应不是JSON格式的。尝试查看响应是否在服务器端转换为json字符串 但由于它以u开头,它最有可能尝试解析未定义的字符串。我建议您不要订阅函数,而应该嵌套如下承诺
getItemById(id):Observable<any>{
console.log('idvalue', id);
return this.http.get("http://localhost:3000/getitem"+"/"+ id).then(result => {
return result.json();
}) //this will return promise
.catch((error:any) => Observable.throw('Server Error to get the item'));
}
}
getItemById(id):Observable<any>{
console.log('idvalue', id);
return this.http.get("http://localhost:3000/getitem"+"/"+ id).then(result => {
return result.json();
}) //this will return promise
.catch((error:any) => Observable.throw('Server Error to get the item'));
}
}
updateitem(itemid){
let updatedresult;
console.log("toupdateid", itemid);
this.dataService.getItemById(itemid)
.then(
res=> {
this.res =JSON.parse(res);
this.newSession.trainingName =res["TrainingName"],
this.newSession.description = res["Description"];
console.log('newsession', this.newSession);
this.getFormdetails();
}).catch(err => {
this.apiError = err
})
)
}