【问题标题】:How to convert JSON value to string in angular 4?如何将 JSON 值转换为角度 4 中的字符串?
【发布时间】:2017-06-17 17:40:56
【问题描述】:

我有一个这样的 json 对象: {path: "images/125/17062017/home.jpg"}.它来自rest api。 我想得到这条路径'images/125/17062017/home.jpg'。我需要 将该路径存储在字符串变量中。我试过这样。 JSON.parse(response).pathresponse.path。但是这些方法都行不通。

 fileChange(event: any) {
    const fileList: FileList = event.target.files;
    if(fileList.length > 0) {
     let file: File = fileList[0];
     this.fileUploadService.saveOwnImageFile(file)
      .subscribe( (response: any) =>{
          console.log(response);   // response = {path:'images/125/17062017/home.jpg'}
          let value = JSON.parse(response);  // getting error here
          console.log(value);
      });
     }
}

【问题讨论】:

  • response.json()?
  • 这是为什么呢?不能只写let value = response.path 吗?
  • 不工作。我试过这种方式
  • 有什么问题?你能提供一个plnker吗?
  • @SathishKotha 我的解决方案是否有效或需要更多帮助

标签: javascript json angular typescript


【解决方案1】:

既然你说你想得到'images/125/17062017/home.jpg'的值,你应该使用let value = response.path;

JSON.stringify(response) 将返回字符串 { "path" : "images/125/17062017/home.jpg" }

【讨论】:

  • 我的项目中有缓存。我清理了它。现在 response.path 正在工作,谢谢 robbannn
  • 不客气!如果您觉得此答案有用,请务必点赞。
【解决方案2】:

JSON.stringify() JSON.stringify() 使用JSON.stringify(..);

fileChange(event: any) {
    const fileList: FileList = event.target.files;
    if(fileList.length > 0) {
     let file: File = fileList[0];
     this.fileUploadService.saveOwnImageFile(file)
      .subscribe( (response: any) =>{
          console.log(response);   // response = {path:'images/125/17062017/home.jpg'} 
/////////////////////////////////////////////////////////////////////////////
          let value = response.json().path.toString();
     ///// note your object is response
/////////////////////////////////////////////////////////////////////////////
          console.log(value);
      });
     }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 2019-01-16
    • 1970-01-01
    • 2022-06-10
    • 2020-03-20
    • 2020-08-08
    • 1970-01-01
    相关资源
    最近更新 更多