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

Mapping the JSON values to the UI fields in Angular 4

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

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

Error: SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse ()

打字稿代码

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 对象本身

从服务中 return

服务器发送无效 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'));
       }
}

并在您的 updateItem 上

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