在rxjs ajax回调中解析JSON回调不起作用
我想在Angular2中解析ajax回调中的JSON字符串。
我打电话response.json())
并做了console.log()
它工作正常。在rxjs ajax回调中解析JSON回调不起作用
这是我试图解析JSON:
{
"success": true,
"data": {
"id": "14cf4717-f5b6-4002-96b2-321324fc4077",
"number": "1234",
"sections": [
{
"id": "53f43dd7-4c93-4925-a51d-c6f81f314275",
"description": "Test",
"created_at": "2017-10-07 15:08:01",
"updated_at": "2017-10-07 15:08:01",
"lines": [
{
"id": "73fab07f-4401-43a4-99a4-13c891907ea7",
"product_id": "62aa5388-712d-4ab1-9e64-6849889194d1",
"product_name": "Product",
"product_description": "test",
"product_type": "product",
"quantity": "1.00",
"product": {
"id": "62aa5388-712d-4ab1-9e64-6849889194d1",
"name": "Product",
"description": "test"
}
}
]
}
],
"notes": []
}
}
在这个函数:就像预期
public getQuotation(quotationId: string, callback: Function) {
this.http.get('/quotation/' + quotationId).subscribe((response) => {
const responseJson = response.json();
console.log(responseJson);
callback(null);
},() => {
callback(null);
});
}
但是,当我加入这行低于的console.log()
: const quotation = <FinBaseModel>(responseJson.data);
public getQuotation(quotationId: string, callback: Function) {
this.http.get('/quotation/' + quotationId).subscribe((response) => {
const responseJson = response.json();
console.log(responseJson);
const quotation = <FinBaseModel>(responseJson.data);
callback(quotation);
},() => {
callback(null);
});
}
然后lines
阵列是空的...
我不明白怎么可能是因为我做的console.log()
之前,我尝试将其转换为FinBaseModel
有谁知道这是如何可能的,我怎么能解决它?
而不是使用JSON.parse你可以做这样的:
this.http.get('/quotation/' + quotationId)
.map(response=> response.json())
.subscribe((responseData) => {
console.log(responseData);
});
的console.log参照打印的对象。印刷发生的时间会发生变化,可能是回调。
console.log(responseJson.data)
const quotation = <FinBaseModel>(responseJson.data);
callback(quotation);
你是对的!我在看错地方。我将对象绑定到HTML中的另一个组件,并在该组件中对象发生了变化。 –
宽度您现在提供的信息我无法帮助您的解决方案。但我可以帮助您正确调试代码: 以查看实际值,如果在您记录日志时更改了值,则必须记录其克隆以确保回调不会更改它。因此请用console.log(JSON.parse(JSON.stringify(response.data)))
更改您的console.log(response.data)
。更改这两个日志并比较结果。我认为这会帮助你理解它并没有改变,但你的回调正在改变它。因为TypeScript类型实际上并没有做任何事情,只是提供你输入的保险和准确性。
使用HttpClient。 Documentation
这应该这样做:
http.get<ItemsResponse>('/api/items').subscribe(data => {
// data is now an instance of type ItemsResponse, so you can do this:
this.results = data.results;
});
getQuotation(quotationId: string, callback: Function) {
this.http.get<FinBaseModel>('/quotation/' + quotationId).subscribe((data) => {
// call your callback here and pass 'data'
// callback(data)
// or return the value and consume it no need to json to
return data
}
提供一个[MCVE] – charlietfl
猜你解析它在回调到一些AJAX请求? – llama
@llama是的,我更新了我的文章 –