我该如何处理POST响应

时间:2017-10-20 09:34:13

标签: angular

嘿我试图通过角度POST从我的服务器获取一些数据我得到了我发送的参数,我得到了服务器的响应。我只是无法处理我的回复,实际上得到了我想要的参数。

如果我在我的控制台中查看,我会收到此回复:

data from server Response {_body: " {"data":[{"temperature":"20","dispenses":5,"lates…08:36:15","latest_reset":"2017-10-15 08:42:47"}]}", status: 200, ok: true, statusText: "OK", headers: Headers, …}

我怎么去抓温度?或者我应该改变我的返回JSON?请指导我正确的方向

我的角度代码:

getCustomerData()
    {
        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        let urlSearchParams = new URLSearchParams();
        urlSearchParams.append('customerID', this.customerID);
        //urlSearchParams.append('password', 'wtf');
        let body = urlSearchParams.toString()

       this.http.post('HIDDEN BUT WORKS',body,{headers: headers}).subscribe(data => {
        // Read the result field from the JSON response.
        console.log('data from server', data);
        let jsonResponse = data.json();
        //console.log('nextstep',data.temperature);
        console.log('hmm',jsonResponse._body.data.temperature);
        //console.log('size',data.toString);
    },(error) => {
        console.log('error', error);

      });
    }

我的回复代码:

while ($stmt->fetch()) {        
            $json[] = array(
            'temperature' => $temperature,
            'dispenses' => $dispenses,  
            'latest_cleaning' => $latest_cleaning,      
            'latest_reset' => $latest_reset     
            );          
        }


        $finalresult['data'] = $json;

        //logToFile('data.log',json_encode($finalresult));
        echo json_encode($finalresult);

2 个答案:

答案 0 :(得分:1)

试试这样:

this.http.post('HIDDEN BUT WORKS',body,{headers: headers}).map(response => response.json()).subscribe(data => {
    console.log('data', data);
})

答案 1 :(得分:1)

使用您的代码,您应该:

this.http.post('HIDDEN BUT WORKS',body,{headers: headers})
.map(response => response.json())
.subscribe(data => {
    console.log('temperature', data[0].temperature);
})

您还可以使用data[0]访问其他媒体资源。