试图学习$ resource。我怎么能在这里使用自己的api?

时间:2015-09-25 18:37:17

标签: javascript angularjs

您好我正在关注可在此处找到的教程:http://www.sitepoint.com/creating-crud-app-minutes-angulars-resource/

services.js中,作者提供了以下代码来使用自己的API:

angular.module('movieApp.services', []).factory('Movie', function($resource) {
  return $resource('http://movieapp-sitepointdemos.rhcloud.com/api/movies/:id', { id: '@_id' }, {
    update: {
      method: 'PUT'
    }
  });
});

我使用CRUD函数创建了自己的API。我想知道:我该如何使用它呢?该代码位于/routes/CRUD.js,链接为/posts/posts/:id

我很困惑我是否需要修改作者的代码,并链接到我的CRUD.jslocalhost:3000/posts/:id

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:1)

angular.module('movieApp.services', []).factory('Movie', function($resource) {     
    // post  and pud body data 
    function setRequestData(data) {
        var requestData = new Object();
        requestData.movie= data;
        return angular.toJson(requestData);
    }
  return $resource('localhost:3000/posts/:id', { id: '@_id' }, {
    }, {      
        'get': {
        method: 'GET',
        headers: {"Content-Type": "application/json"},
        },
        'new': {
        method: 'POST',
        headers: {"Content-Type": "application/json"},
        transformRequest: setRequestData
        },
        'delete': {
        method: 'DELETE',
        headers: {"Content-Type": "application/json"},
        transformRequest: setRequestData
        },
        'update': {
        method: 'PUT',
        headers: {"Content-Type": "application/json"},
        transformRequest: setRequestData
        }
    });
  });
});