【问题标题】:How can I access value returned after Angular $resource $save()?如何访问 Angular $resource $save() 之后返回的值?
【发布时间】:2018-01-10 00:38:26
【问题描述】:

我正在使用 PHP CRUD Api 来服务一个简单的 AngularJS 列表应用程序。

当我向数据库添加新项目时,我想刷新列表以显示新项目。

我的想法是在 $save 成功回调中将数据推送到列表数组中。这很好用,但我需要知道由 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 () {

    });

这是在插入新记录后刷新应用程序的最佳方式还是我用错了方式?

【问题讨论】:

    标签: php angularjs


    【解决方案1】:

    以防万一将来有人偶然发现这个问题,问题不在于 $save 函数,而是 php CRUD Api 的问题 - 它返回了最后插入的 ID,但不是 JSON编码格式。

    一旦我更改了 php Api 以返回 JSON 编码的 ID(例如 {"id": "185"}),我就可以访问 res.id

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-21
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      • 2015-12-14
      相关资源
      最近更新 更多