2016-10-13 41 views
0

通过使用PHP我呼应从SQL Server响应:从PHP接收JSON到角2的HttpModule

echo json_encode($total); 

就像一个测试,我赞同之前,我运行error_log中(json_encode($总计))其中输出的对象为:

[{"address":"Mitchell Hwy", 
    "description":"Nyngan Eastbound STC", 
    "site_name":"T0242", 
    "heading":"East", 
    "vehicle_class":"B double", 
    "vehicle_class_id":"10", 
    "avg_speed":"69.27", 
    "volume":"46"}] 

这正是我想在Angular 2的http响应中收到的内容。我的角2的代码是:

let headers = new Headers(); 
    headers.append('Content-Type', 'application/json'); 

    return this.http.post(url, sentArray,{ 
     headers: headers 
    }).subscribe(
     result => returnedJSON = result, 
    () => console.log("Failed..."), 
    () => console.log(returnedJSON) 
    ); 

这在控制台中,该响应消息“身体”是,我想返回的PHP代码打印“响应”对象。

Response {_body: "[{"address":"Mitchell Hwy","description":"Nyngan E…_id":"Total","avg_speed":"67.35","volume":"262"}]", 
status: 200, 
ok: true, 
statusText: "OK", 
headers: Headers…} 

我的问题是: 为什么我会收到一个完整的响应对象?这是因为我使用POST HTTP请求 - 还是只是Angular 2接收响应的方式?我如何隔离响应主体?

我假设我在PHP中正确地做了所有事情,因为我记录了我想要的确切输出。我认为这与我的Angular 2代码有关...

+0

在'subscribe'回调中使用'response.json()'可以做到这一点。 –

+0

Harry Ninh - 谢谢:) 如果您将它作为答案发布,我将删除我的答案并将其标记为正确(如果您喜欢)。 – fila

+0

没关系,改进你的工作并将其标记为完成。我完全没问题:) –

回答

0

我很抱歉 - 如果其他人被卡在同一点,答案很简单。使用'.text()'隔离响应主体。我发现这个在这里: https://angular.io/docs/ts/latest/api/http/index/Response-class.html

let headers = new Headers(); 
    headers.append('Content-Type', 'application/json'); 

    return this.http.post(url, sentArray,{ 
     headers: headers 
    }).subscribe(
     result => returnedJSON = result.text(), //the '.text()' was the issue. 
    () => console.log("Failed..."), 
    () => console.log(returnedJSON) 
    ); 

编辑

哈利宁提供了一个更好的解决方案。使用'result.json()'而不是'.text()'。 'Result.json()'返回对我来说更好的对象数组。