简体   繁体   English

具有$ resource的Angular服务/工厂

[英]Angular Services/Factories with $resource

I'm a Web Developer new to AngularJS. 我是AngularJS的Web开发人员。 I've been reading @toddmotto's Angular styleguide ( https://github.com/toddmotto/angularjs-styleguide ). 我一直在阅读@toddmotto的Angular样式指南( https://github.com/toddmotto/angularjs-styleguide )。 I am currently building a CRUD app grabbing data via a RESTful API. 我目前正在构建一个通过RESTful API捕获数据的CRUD应用程序。

I'm a bit stuck on services and/or factories. 我对服务和/或工厂有些困惑。

I had it working previously (code below) but since looking at Todd's styleguide - I would like to move my logic from the controller to the service/factory but I'm not sure how to get what I had before working in the new structure. 我以前使用过它(下面的代码),但是由于查看了Todd的样式指南-我想将逻辑从控制器转移到服务/工厂,但是我不确定在使用新结构之前如何获得所拥有的东西。

Does anybody have any ideas? 有人有什么想法吗?

Previous UserService.js 以前的UserService.js

(function () {
    'use strict';

    function UserService($resource) {
        return $resource('https://api.path.com/users/:id', { }, {
            query: {
                method: 'GET'
            },
            create: {
                method: 'POST'
            },
            update: {
                method: 'PUT'
            },
            delete: {
                method: 'DELETE'
            }
        });
    }

    angular
        .module('app')
        .factory('UserService', UserService);
})();

Currently, I have: 目前,我有:

UserController.js UserController.js

(function () {
    'use strict';

    function UserController(UserService) {
        var _this = this;

        UserService
            .getUsers()
            .then(function (response) {
                _this.users = response;
                console.table(response);
            });
        };
    }

    angular
        .module('app')
        .controller('UserController', UserController);
})();

UserService.js UserService.js

(function () {
    'use strict';

    function UserService($resource) {
        var service = {};

        service.getUsers = function () {
            return $resource('https://api.path.com/users');
        };

        return service;
    }

    angular
        .module('app')
        .factory('UserService', UserService);
})();

EDIT 编辑

    var resource =  $resource(baseUrl + '/users/:id', { }, {
        query: {
            method: 'GET'
        },
        create: {
            method: 'POST'
        },
        update: {
            method: 'PUT'
        },
        delete: {
            method: 'DELETE'
        }
    });

    service.getUsers = function () {
        return resource.query().$promise;
    };

Try this: 尝试这个:

service.getUsers = function () {
    return $resource('https://api.path.com/users').query().$promise;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM