模块和控制器之间AngularJS共享REST服务 [英] AngularJS shared REST service between modules and controllers

查看:75
本文介绍了模块和控制器之间AngularJS共享REST服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有一组资源的工厂消耗REST API和使用,在我所有的模块和控制器。我很困惑,究竟应该如何分离,如何从控制器访问工厂。

作为一个例子,假设我有:

  // rest.js
angular.module('myApp.rest',['ngResource'])
    .factory('书',函数($资源){
        返回$资源(API /书',{},{
            getBook:{
                方法:GET
            },
        });
    })

下面是主要的模块对myApp

  // app.js
 angular.module('对myApp',[        ngRoute',
        ngResource',        app.rest',
        app.library    ])
      的.config(['$ routeProvider',函数($ routeProvider){
            $ routeProvider。
                当('/书',{
                    templateUrl:someTemplate',
                    控制器:'LibraryCTRL',
                });

现在我想有一个名为 app.library 可以使用图书资源其他模块。如何依赖注入会是什么样子?

更重要的问题:这是做的正确方法?我的意思是它更好地整图书厂重视对myApp 或使用一个单独的对myApp .rest 模块?

  // library.js

    .module('myApp.library',['ngResource'])// INJECT REST MODULE在这里?
    .controller('LibraryCtrl',图书馆);//此处INJECT图书资源?
图书馆$注射= [];//使用本书在此构造
函数库(){    VAR VM =这一点;    //使用它
    Book.getBook(功能(数据){
         vm.book =数据;
    });
}


解决方案

让我们抽象问题

据我所知你想它可以在所有模块和控制器,负责消费REST API

用于工厂定制服务

所以你将有 serviceModule.js

  VAR ServiceApp = angular.module('ServiceApp',[]);
ServiceApp
        。厂(
                restControllerService',
                [
                        $ HTTP,
                        功能($ HTTP){                            VAR doRequest =
                            功能(URL){
                                    返回$ HTTP({
                                        方法:'得到',
                                        网址:网址,
                                       标题:{
                                       内容类型:应用/ JSON
                                                 }
                                    });
                                    });
                                }                            }
                            返回{
                                getBook:功能(){
                                    返回doRequest(API /书');
                                }
                            };
                        }]);

您可以注入,像任何其他模块中的

 变种库= angular.module('libraryModule',[ServiceApp]);
libraryModule.controller('LibraryCtrl',[
        '$范围',
        restControllerService',
        功能($范围,restControllerService){            $ scope.book = NULL;            $ scope.getbook =功能(){                    restControllerService.getbook(API /书)。成功(
                            功能(数据){
                                $ scope.book =数据;
                            })错误(函数(){
                        $ scope.book = NULL;
                    });
                }
            };

I need to have a set of resource factories to consume a rest api and use that in all of my modules and controllers. I'm confused as to how this should be separated and how to access the factories from controller.

As an example, let's assume I have:

// rest.js
angular.module('myApp.rest', ['ngResource'] )
    .factory('Book', function ($resource) {
        return $resource('api/book', {}, {
            getBook: {
                method: 'GET'
            },
        });
    })

Here's the main module as myApp:

 // app.js
 angular.module('myApp', [

        'ngRoute',
        'ngResource',

        'app.rest',
        'app.library'

    ])
      .config(['$routeProvider', function ($routeProvider) {
            $routeProvider.
                when('/book', {
                    templateUrl: 'someTemplate',
                    controller: 'LibraryCTRL',
                });

Now I want to have another module called app.library which can use Book resource. How the Dependency Injection would look like?

More important question: Is this the right way to do it? I mean is it better to attach the whole Book factory to myApp or use a separate myApp.rest module?

// library.js
angular
    .module('myApp.library', ['ngResource']) // INJECT REST MODULE HERE?
    .controller('LibraryCtrl', Library);

// INJECT BOOK RESOURCE HERE? 
Library.$inject = [];

// USE BOOK IN THIS CONSTRUCTOR
function Library() {

    var vm = this;

    // USING IT
    Book.getBook(function(data){
         vm.book = data;
    });
}

解决方案

let's Abstract the problem

as i understand you want to make custom factory "service" which can be used in all modules and controllers that is responsible for consuming rest api

so you will have serviceModule.js

var ServiceApp = angular.module('ServiceApp', []);
ServiceApp
        .factory(
                'restControllerService',
                [
                        '$http',
                        function($http) {

                            var doRequest = 
                            function(URL) {
                                    return $http({
                                        method : 'get',
                                        url :  URL, 
                                       headers : {
                                       'Content-Type' :'application/json'
                                                 }
                                    });
                                    });
                                }

                            }
                            return {
                                getBook : function() {
                                    return doRequest('api/book');
                                }
                            };
                        } ]);

you can inject that in any other module like that

var library = angular.module('libraryModule', [ "ServiceApp" ]);
libraryModule.controller('LibraryCtrl', [
        '$scope',
        'restControllerService',
        function($scope,restControllerService) {

            $scope.book = null;

            $scope.getbook = function() {

                    restControllerService.getbook('api/book').success(
                            function(data) {
                                $scope.book = data;
                            }).error(function() {
                        $scope.book = null;
                    });
                }
            };      

这篇关于模块和控制器之间AngularJS共享REST服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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