Home  >  Q&A  >  body text

angular.js - angular跨文件注入服务

假设在 a.js 定义了 service A,b.js 定义了一个 controller B,如何在B中注入服务A

PHP中文网PHP中文网2714 days ago572

reply all(3)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-05-15 16:58:45

    angular cross-file injection service?
    Looking at your question, I think the questioner has a unclear concept and should understand the following basic concepts.
    1. The organizational structure of the angular code you write is not divided by files.
    2. Angular has been abstracted into components such as controller, service, and directive. You can write these things in multiple files, or you can write them all in one file. To make your code effective, just load it in HTML. In order to make the program more readable, we generally require that a component be defined in a separate file and follow a good directory structure.
    3. Code division is done by modules. For example, if you use bower to install a certain package, you need to write the dependent module when defining your module, then the component defined in the dependent module will be valid. This point talks about the module level.
    4. What is injection service? Although you load a module, all the code inside it is loaded. But which services each controller depends on, and how Angular needs to find them, you still need to tell Angular. At this time, dependency injection is needed. This point talks about the controller level.

    To sum up, you can just load it in the most common way by controllerX.$inject = ['serviceX'];. controllerX.$inject = ['serviceX']; 直接最普通的方式加载就行了。
    如果没有生效,那应该是以下原因:
    1. 没有引入js文件。
    2. 没有加载这个service所在的模块。angular.module('MyApp',['ModuleX'])If it does not take effect, it should be due to the following reasons:
    1. The js file is not imported.

    2.

    The module where this service is located is not loaded. angular.module('MyApp',['ModuleX']) will do the trick.

    3.

    But please note that your own module MyApp can be used multiple times, but dependencies can only be defined once, otherwise the referenced modules will not be the same module. 🎜That’s it you can🎜
    angular.module('MyApp',['ModuleX'])
        . controller('ControllerA', ControllerA);
    angular.module('MyApp')
        . controller('ControllerB', ControllerB);
    🎜But it must not be possible🎜
    angular.module('MyApp',['ModuleX'])
        . controller('ControllerA', ControllerA);
    angular.module('MyApp',['ModuleX'])
        . controller('ControllerB', ControllerB);
    🎜Check these 3 points. If it still doesn’t work, continue to post the code for discussion. 🎜

    reply
    0
  • 怪我咯

    怪我咯2017-05-15 16:58:45

    First of all, this problem can be divided into two situations. One is that service A and controller B both belong to the same module. The other situation is that neither service A nor controller B belongs to the same module.

    Let me post the code part first:
    First is index.html, the code is as follows:

    <body ng-app="MyApp">
    <h1>依赖注入</h1>
    <p ng-controller="MyController as vm">
        <button ng-click="vm.getUsers()">getUsers(依赖同一个模块的服务)</button>
        <button ng-click="vm.getUsers2()">getUsers2(依赖不同模块的服务)</button>
        <p ng-repeat="v in vm.users">{{v.avatar_url}}</p>
        <p ng-repeat="v in vm.users2">{{v.id}}</p>
    </p>
    </body>

    Also note that index.html中引入a.js b.js c.js

    a.js should be introduced in

    b.jsThe code part is as follows:

    angular.module('MyApp',['MyModule'])
        .controller('MyController', MyController);
    
    MyController.$inject = ['MyService', 'MyService2'];
    
    function MyController(MyService, MyService2){
        var vm = this;
        vm.users = [];
        vm.users2 = [];
        vm.getUsers = getUsers;
        vm.getUsers2 = getUsers2;
    
        function getUsers(){
            console.log('依赖的是同一个模块的服务');
            MyService.getData()
                .then(function(res){
                    vm.users = res.data;
                })
        }
    
        function getUsers2(){
            console.log('依赖的是不同模块的服务');
            MyService2.getData()
                .then(function(res){
                    vm.users2 = res.data;
                })
        }
    }

    c.jsThe code part is as follows:

    angular.module('MyApp')
    .service('MyService', MyService);
    
    MyService.$inject = ['$http'];
    
    function MyService($http){
        var url = 'https://api.github.com/users';
        var service = {
            getData: getData
        };
    
        return service;
    
        function success(res){
            return res;
        }
    
        function fail(e){
            console.log(e);
        }
    
        function getData(){
            return $http.get(url)
                .then(success)
                .catch(fail);
        }
    }

    The code part is as follows:

    angular.module('MyModule',[])
        .service('MyService2', MyService);
    
    MyService.$inject = ['$http'];
    
    function MyService($http){
        var url = 'https://api.github.com/users';
        var service = {
            getData: getData
        };
    
        return service;
    
        function success(res){
            return res;
        }
    
        function fail(e){
            console.log(e);
        }
    
        function getData(){
            return $http.get(url)
                .then(success)
                .catch(fail);
        }
    }

    In addition, you can also go here to see a demo written, which is the running result of the above code.

    It should be noted that if it is the same module, the service can be used directly by injecting it into the controller; if it is a different module, then it is necessary to inject the module you want to depend on in the main module. in the main module, and then can also be used in the controller. 🎜 🎜You should understand it almost after reading the code. If there is anything you still don’t understand, you can also read an article I wrote before. I hope it can help you. 🎜

    reply
    0
  • 迷茫

    迷茫2017-05-15 16:58:45

    I think the questioner doesn’t understand that the data model (Model)和视图(View)之间是通过控制器 (controller) in angularjs has a two-way data binding (Data Binding) relationship.

    A data model (M) can have multiple views (V), which means one controller (C) can control multiple views. There may be business logic relationships between these views, for which multiple controllers are created so that one controller controls one view. However, it is possible that these controllers have the same content and can be extracted. Then there are two ways:

    Method 1 (inheritance method, common bad situation): Multiple controllers inherit a common controller.
    Method 2 (angularjs service): Extract common content into one or more services and let the controller call (call different services on demand)

    You can compare the two. Service is more modular and reusable.

    I think, after understanding this process in this way, you will probably know the Dependency Injection Service mentioned above.

    reply
    0
  • Cancelreply