如何在Angular中使用$ resource来使用RESTful api

时间:2014-03-23 07:55:59

标签: angularjs mean-stack

我试图在MEAN堆栈中添加一些基本的CRUD功能。我已经创建了一个可以运行的RESTful服务,而且我对如何连接所有内容感到困惑。我可以让它工作,但我想确保我以最好的方式做事,而不是创造一个不必要的黑客。

我对一个人的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>

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

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

这适用于我原来未经修改的模板。这是使用RESTful apis的最佳或正确方法吗?还有更好的方法吗?

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

1 个答案:

答案 0 :(得分:1)

你的api应该是这样的:

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

然后,如果你想通过id获取,你应该使用get方法,或者如果你想要获得所有人,你应该使用query方法。你的错误是你在按id

时会返回单个对象