AngularJS - 在工厂中使用 Restangular 使用 REST API [英] AngularJS - Consuming REST API with Restangular in a factory

查看:37
本文介绍了AngularJS - 在工厂中使用 Restangular 使用 REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解如何在控制器中使用 Restangular,但我的想法是,Restangular 本质上是一个 ORM.

I understand how to use Restangular in a controller, however my thoughts are that Restangular is essentially an ORM on steroids.

ORM 不应了解应用程序的状态.这是控制器的工作.

The ORM shouldn't have any knowledge of the state of the application. That is the job of the controller.

我还想重用对 ORM 的查询,因此,我认为应该在服务中使用 Retangular.

I also want to re-use queries to the ORM, and as such, I believe that Restangular should be used inside a service.

我的问题是我是一个 js/angularjs 和 resangular 菜鸟,只有大约 2-3 个月的前端经验.

My problem is that I am a js / angularjs and restangular noob, having only about 2-3 months exp with anything front-end.

我的控制器:

app.controller('AdminSupplierIndexController', 
    ['$scope', '$stateParams', '$state', 'Supplier', 
    function ($scope, $stateParams, $state, Supplier) {


        $state.reload();

        Supplier.getAll.then(function (suppliers) {
            $scope.suppliers = suppliers;
        });
}]);

app.controller('AdminSupplierDetailController', 
    ['$scope', '$stateParams', 'Supplier', 
    function ($scope, $stateParams, Supplier) {

        Supplier.getOne({ supplierId : $stateParams.supplierID}).then(function(supplier) {
            $scope.supplier = supplier;
        });
}]);

我的工厂

app.factory('Supplier', ['Restangular', function (Restangular) {
    return {
        getAll: Restangular.all('supplier').getList(),
        getOne: Restangular.one('supplier', supplierId).get()
    };
}]);

我的 Supplier.getAll 方法工作正常 - 我可以列出供应商工厂的所有供应商.我的问题是我的 Supplier.getOne 方法.

My Supplier.getAll method works fine - I can list all the suppliers from the Supplier factory. My problem is with my Supplier.getOne method.

问题1:如何将supplierId 注入工厂?我收到 ReferenceError:supplierId 未定义问题 2:考虑到当 Retangular 已经提供这些方法时,我必须为每个工厂创建单独的 C-R-U-D 方法,我是否试图过度设计?

Question 1: How do I inject the supplierId into the factory? I am getting ReferenceError: supplierId is not defined Question 2: Am I trying to over-engineer things considering that I would have to create individual methods for C-R-U-D for every single factory when these methods are already provided by Restangular?

推荐答案

我知道这是旧的,但另一种方法是将它包装在一个函数中.这样,您就可以在服务/方法中保留任何其他逻辑.

I know this is old, but an alternate way would just be to wrap it within a function. This way, you can keep any other logic within the service/method.

app.factory('Supplier', ['Restangular', function (Restangular) {
  return {
    getAll: Restangular.all('supplier').getList(),
    getOne: function(supplierId) {
      return Restangular.one('supplier', supplierId).get()
    }
  };
}]);

这篇关于AngularJS - 在工厂中使用 Restangular 使用 REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆