2016-11-19 54 views
0

我正在使用PHP CRUD Api來服務一個簡單的AngularJS列表應用程序。

當我向數據庫添加新項目時,我想刷新列表以顯示新項目。

我的想法是將數據推送到$ save success回調中的列表數組中。這很好,但我需要知道由PHP API編寫的記錄的'id'。

PHP的API不傳回lastInsertId()因爲在代碼中可以看出

function create($table, $data) { 
    $fields = $this->filter($table, $data); 

    $sql = "INSERT INTO " . $table . " (" . implode($fields, ", ") . ") VALUES (:" . implode($fields, ", :") . ");"; 

    $bind = array(); 
    foreach($fields as $field) 
     $bind[":$field"] = $data[$field]; 

    $result = $this->run($sql, $bind); 
    return $this->db->lastInsertId(); 
} 

$db = new db(); 
$rowId = $db->create($table,$data); 
$requestContentType = $_SERVER['HTTP_ACCEPT']; 
$this ->setHttpHeaders($requestContentType, $statusCode); 
$response = $this->encodeJson($rowId); 
echo $response; 

的問題是,我不知道如何使用代碼來訪問lastInsertId()在成功回調下方

data.$save() 
    .then(function (res) { 
     // push the new data in to the list array here - how do I access the lastInsertId() that is returned from the Api? 
    }) 
    .catch(function (req) { 
     // error 
    }) 
    .finally(function() { 

    }); 

這是插入新記錄後刷新應用程序的最佳方式,還是我以錯誤的方式進行操作?

回答

0

以防萬一任何人在將來遇到這個問題時,這個問題不是$save函數,它是php CRUD Api的問題 - 它返回最後插入的ID好,但不是以JSON編碼格式。

一旦我改變了PHP API返回ID JSON編碼(例如{"id": "185"})我可以訪問res.id

相關問題