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

问题描述 投票:0回答:2

我正在尝试使用带有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'));
       }
}
node.js mongodb angular mean-stack
2个回答
2
投票
    .map(result =>{ this.result = result.json();
    console.log('getitembyid' ,result.json())})

将其更改为

    .map(result => result.json())

并删除ts代码中的JSON.parse,因为它现在将作为JSON对象从服务返回


0
投票

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

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

但是因为它从你开始,它最有可能试图解析一个未定义的字符串。我是sugest而不是订阅功能你应该像下面这样嵌套承诺。

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
    })
  )
}
© www.soinside.com 2019 - 2024. All rights reserved.