【问题标题】:Can't route properly Angular无法正确路由 Angular
【发布时间】:2016-12-25 08:59:57
【问题描述】:

尝试为 TodoApp 编写 Angular 的 REST API,为 ADD、UPDATE、GET ALL 设置路由,但停留在 DELETE 方法上。 我的角度控制器:

angular.module('todoListApp')
.controller('todoCtrl', function($scope, Todo) {
  $scope.deleteTodo = function(todo, index) {
    $scope.todos.splice(index, 1);
    todo.$delete();
    console.log("<<" + todo.name + ">> deleted.");
 };

角度服务:

angular.module('todoListApp')
.factory('Todo', function($resource){
  return $resource('/todos/', {id: '@id'}, {
    update: {
      method: 'PUT'
    },
    save: {
      method: 'POST'
    },
    delete: {
      method: 'DELETE',
      params: {id: '@id'}
    }

  });
});

我的 Spark 控制器:

    delete("/todos", "application/json", (req, res) -> {
        Todo todo = gson.fromJson(req.body(), Todo.class);
        if (todo == null) throw new ApiError(404, "Could not find todo.");
        todoDao.delete(todo);
        return todo;
    }, gson::toJson);

    delete("/todos/:id", "application/json", (req, res) -> {
        int id = Integer.parseInt(req.params("id"));
        Todo todo = gson.fromJson(req.body(), Todo.class);
        if (todo == null) throw new ApiError(404, "Could not find todo.");
        todoDao.delete(todo);
        return todo;
    }, gson::toJson);

当单击删除按钮 (ng-click="deleteTodo(todo, $index)") 时,第一个控制器被调用,但不是第二个。我做了两个只是为了调试。 错误信息是:

angular.js:10661 DELETE http://localhost:4567/todos?id=3 404 (Not Found)

在哪里我可以看到正确的 id 参数,但为什么控制器没有捕捉到它?

【问题讨论】:

  • delete("/todos/:id", "application/json", (req, res) -> { int id = Integer.parseInt(req.params("id")); Todo todo = gson.fromJson(req.body(), Todo.class); if (todo == null) throw new ApiError(404, "Could not find todo."); todoDao.delete(todo); return todo; } , gson::toJson);
  • 有问题的 Spark 控制器 body = 此 url 的 Java 控制器,或者您的意思是什么?
  • 抱歉,我弄糊涂了。我会删除我的评论。 (你也可以删除你的)

标签: java angularjs angular-ui-router spark-java


【解决方案1】:

$Resource

给定一个模板 /path/:verb 和参数 {verb:'greet', salutation:'Hello'} 导致 URL /path/greet?salutation=Hello

但您的 API 需要 /parameter

【讨论】:

    【解决方案2】:

    错误出现在 angular .factory 代码中,一定有

    angular.module('todoListApp')
    .factory('Todo', function($resource){
      return $resource('/todos/:id', {id: '@id'}, {
        update: {
          method: 'PUT'
        },
        save: {
          method: 'POST'
        },
        delete: {
          method: 'DELETE',
          params: {id: '@id'}
        }
    
      });
    });
    

    在返回的 $resource 行中丢失了 ':id'。

    【讨论】:

      猜你喜欢
      • 2020-04-02
      • 2017-07-21
      • 1970-01-01
      • 2015-04-14
      • 1970-01-01
      • 2016-01-25
      • 2020-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多