2

我正在尝试向 MEAN 堆栈添加一些基本的 CRUD 功能。我创建了一个可以工作的 RESTful 服务,但我对如何将它全部连接起来感到困惑。我可以让它工作,但我想确保我以最好的方式做事,而不是造成不必要的黑客攻击。

我的单个 Person 的 api 路由是这样的:

// Find one person
app.get('/api/person/:id', function(req, res) {
  Person.find ( {_id: req.params.id },
    function(err, data){
      res.json(data);
    }
  )});

 // Find group of people
 app.get('/api/person', function(req, res) {
   // use mongoose to get all people in the database
   Person.find(function(err, data) {
     res.json(data); 
 }); 

这似乎有效,如果我使用 ID 访问 URI,例如 localhost://3000/api/person/23423434,我会看到如下 JSON 数据:

[
  {
    "_id": "532d8a97e443e72ef3cb3e60",
    "firstname": "Horace",
    "lastname": "Smith",
    "age": 33
  }
]

这告诉我我的 RESTful api 的基本机制正在工作。现在我想在模板中显示带有角度的数据,如下所示:

<h3>{{ person.firstname + ' ' + person.lastname }} </h3>

为此,我只需要使用 get() 或 query() 创建一个 $scope.person 对象。这是我的应用程序的相关部分:

angular.module('crudApp', ['ngRoute', 'ngResource'])
  .config(['$routeProvider', function($routeProvider){
    $routeProvider
      .when('/api/person/:id',
        {
          templateUrl: 'partials/person.html',
          controller: 'PersonCtrl'
        });
      }])
      .factory('Person', function($resource){
        return $resource('api/person/:id', { id: '@_id'});
      })
      .controller('PersonCtrl', function($scope, $routeParams, Person){
         $scope.person = Person.get( { id: $routeParams.id } ); // Having trouble here!
      });

我遇到的麻烦是 get() 失败并出现错误(错误:[$resource:badcfg])。另一方面,如果我使用 Person.query(),我会返回一个数组,这意味着我需要将我的模板更改为以下内容:

<h3>{{ person[0].firstname + ' ' + person[0].lastname }} </h3>

这可行,但看起来很奇怪,不像我在 Angular 教程中看到的那样。我发现的唯一其他解决方案是在回调中设置 $scope.person :

Person.query({ id: $routeParams.id  }, function(person){
  $scope.person = person[0];
});

这适用于我的原始未修改模板。像这样使用 RESTful api 是最好的还是正确的方法?有没有更好的办法?

答案:答案在下面的评论中。我的问题是 api 正在使用 Person.find() 但应该使用 Person.findOne( { _id: req.params.id }); 使用 findOne() 返回单个对象。

4

1 回答 1

1

您的 api 应如下所示:

route -> '/api/person/:id'
    return single person
route -> '/api/person'
    return array of persons

那么如果你想通过id获取,你应该使用get方法,或者如果你想获取所有人,你应该使用query方法。您的错误是通过 id 获取时应返回单个对象

于 2014-03-23T08:05:27.283 回答