问题描述
我正在创建一个爱好应用程序,其中Angular是前端,而Python充当后端。 Angular中的一个组件正在将HTTP GET发送到Python,Python在该HTTP GET上使用jsonpickled对象进行响应。
我想解开(解码)HTTP RESPONSE中收到的jsonpickled对象。 解锁(解码)将发生在Angular的component.ts文件中,该文件接收到HTTP REPSONSE对象。
按照此处的示例文件中的说明进行操作,但不起作用:https://github.com/cuthbertLab/jsonpickleJS(在tests目录下,有testUnpickle.html文件,我曾将其用作参考,但脚本标签中的部分无法执行)
以下是Angular的component.ts文件中的代码:
ngOnInit() {
this.id = this.route.snapshot.params['id'];
this.url = 'http://127.0.0.1:5000/api/restaurants/' + this.id
this.http.get(this.url).subscribe(
response =>
{
this.name = response['name'];
this.location = response['location'];
this.photos = response['photos']; // this is the jsonpickled object,I want to unpickle it so as to get a File Object.
console.log(response)
}
)
}
下面是来自component.html文件的片段:
<body>
<script type="text/javascript" src="../../assets/jsonpickleJS-master/build/jsonpickle.min.js"
data-main= "jsonpickleJS/main"></script>
<script type="text/javascript">
picfileobj = jsonpickle.decode(photos)
console.log("getting decoded file for pic")
console.log(picfileobj)
</script>
</body>
解决方法
可以使用以下代码解码HTTP响应中接收到的jsonpickle对象。
- 从https://github.com/cuthbertLab/jsonpickleJS下载jsonpickle js文件
- 导入angular.json(jsonpickle.min.js)
- 在xyz.component.ts文件中声明var jsonpickle:
- 使用jsonpickle.decode(jsonpickled_object)方法获取原始文件对象。