将 JSON 值映射到 Angular 4 中的 UI 字段



我正在尝试使用Mean Stack和Angular 4进行更新操作。我是这项技术的新手。对于更新对象,我需要根据选择的 id 将值映射到 UI 表单以更新记录。我的数据服务正在以需要更新的 JSON 形式从 MongoDb 数据库中获取记录值。但是,我无法将这些参数设置为打字稿代码中表单上存在的字段。

我正在使用 JSON.parse 方法来实现它,但出现以下错误。

错误:

语法错误:JSON 中位于 JSON.parse (( 位置 0 的意外标记 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();
    }
  )
}

数据服务

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对象本身从服务返回

当服务器发送无效的 json 时,会发生此错误。您需要检查服务器的响应。

这有不同的原因,但最有可能:您正在将请求发送到错误的终结点。因此,您得到的不是 json,而是从您开始的文档,它会尝试解析它。另一个是服务器向您发送非JSON格式的错误响应。尝试查看响应是否在服务器端转换为 json 字符串。

但是由于它从您开始,因此它最有可能尝试解析未定义的字符串。我建议而不是订阅功能,您应该嵌套以下承诺。

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
    })
  )
}

最新更新