Angular 4+MEAN栈更新操作:JSON映射UI表单遇解析错误求助
解决Angular中JSON.parse报错及表单赋值问题
嘿,我来帮你搞定这个问题!你遇到的Error: SyntaxError: Unexpected token u in JSON at position 0错误,本质原因是你尝试对undefined执行JSON.parse()操作了,咱们一步一步来排查和修复:
问题根源分析
先看你的数据服务getItemById方法里的map操作:
.map(result =>{ this.result = result.json(); console.log('getitembyid' ,result.json())})
这里你用了带大括号的箭头函数,但没有返回任何值!箭头函数如果用大括号包裹代码块,必须显式写return,否则默认返回undefined。这就导致组件的subscribe回调里拿到的res是undefined,执行JSON.parse(res)自然就会抛出那个“Unexpected token u”的错误(因为undefined转字符串是"undefined",第一个字符就是u)。
另外还有个小问题:Angular的Http.get()返回的Response对象,调用.json()已经把响应体解析成JavaScript对象了,根本不需要再用JSON.parse()去处理它。
修复步骤
1. 修正数据服务的getItemById方法
让map函数返回解析后的JSON数据:
getItemById(id):Observable<any>{ console.log('idvalue', id); return this.http.get("http://localhost:3000/getitem"+"/"+ id) .map(result =>{ const parsedData = result.json(); console.log('getitembyid' , parsedData); return parsedData; // 必须返回这个值,subscribe才能拿到数据 }) .catch((error:any) => Observable.throw('Server Error to get the item')); }
2. 修正组件的updateitem方法
去掉多余的JSON.parse(),直接使用返回的数据赋值:
updateitem(itemid){ let updatedresult; console.log("toupdateid", itemid); this.dataService.getItemById(itemid) .subscribe( res=> { // 这里直接用res即可,因为服务已经帮你解析好JSON了 this.newSession.trainingName = res["TrainingName"]; this.newSession.description = res["Description"]; console.log('newsession', this.newSession); }, err=> this.apiError = err, () => { this.getFormdetails(); } ) }
额外小建议
如果你的newSession是Angular表单(比如FormGroup实例),更推荐用patchValue或setValue来批量赋值,代码会更简洁:
// 假设newSessionForm是你的FormGroup this.newSessionForm.patchValue(res);
这样会自动匹配表单控件名和返回数据的键名,省去逐个赋值的麻烦。
内容的提问来源于stack exchange,提问作者knowledge20
相关产品推荐
相关产品推荐

