AngularJS - 在工厂消费REST API与Restangular [英] AngularJS - Consuming REST API with Restangular in a factory

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

问题描述

我知道如何在控制器使用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,正因为如此,我认为,应该Restangular服务内部使用。

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和restangular菜鸟,仅有约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:不定义供应商ID
问题2:我是否想要过工程师考虑的事情,我必须创建为每一个工厂,C-R-U-D各个方法时Restangular已经提供了这些方法。

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 - 在工厂消费REST API与Restangular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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