如何将JSON值转换为角度4中的字符串?

问题描述:

我有一个JSON对象是这样的: {path: "images/125/17062017/home.jpg"}。它的从REST API的到来。 我想要得到这个路径'images/125/17062017/home.jpg'。我需要 将该路径存储在字符串变量中。我试过这样。 JSON.parse(response).pathresponse.path。但是这些方法不起作用。如何将JSON值转换为角度4中的字符串?

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); 
     }); 
    } 
} 
+0

response.json()? –

+0

这是为什么?不能只写'let value = response.path'? –

+0

无法正常工作。我试过那种方式 –

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

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

+0

我缓存我project.I洗干净。现在response.path正在工作,感谢robbannn –

+0

不客气!如果你发现这个答案有用,一定要注意。 – robbannn

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