• angular factory service provider


    随着业务越来越复杂,代码也是越来越复杂。

    尤其是controller文件,view->controller->service 的数据处理 service->controller->view的数据处理,单单这两个方向的数据处理也许就会用到非常多的代码。

    导致后续的维护也是越来越难。

    让我们把重心稍微向service偏向吧

    angular有3种方式创建注册自己的service

    1. factory
    2. service
    3. provider

    1,factory主要用来创建一个对象service,我们可以向service添加一些属性,最后return service,当别的controller注入factory时,可以通过service调用我们添加的那些属性。

    app.factory('myFactory',() => {
        let service = {};
        let attr = 'i am attr';
    
        service.getAttr = function(){
           console.log(attr);
        }
        return service;
        
    });
    
    app.controller('myController',(myFactory) => {
        myFactory.getAttr();
    });

    2,service通过new来实例化,因此我们在编写service时,应该注意在service(es6)构造器中定义属性,函数方式中的this属性。

    class Service {
        /*@ngInject*/
        constructor(){
            this.attr = 'i am attr';
        }
        
        getAttr(){
          console.log(this.attr);
        }
    }
    
    app.service('myService',new Service);
    app.controller('myController',(myService
    ) => {myService.getAttr(); });
    
    

    3,provider

          providers 是唯一一种可以传进 .config() 函数的 service,可以在 service 对象启用之前进行一些配置。

    class Provider {
        /*@ngInject*/
        constructor(){
            this.attr = 'i am attr';
            this.$get = () => {
                   return{
                   getAttr:() => {
                        console.log(this.attr)
                    }
            }
        }
    }
    
    app.service('myProvider',Provider);
    app.controller('myController',(myProvider
    ) => {myProvider.getAttr()};    

    特别地,controller只能访问provicer中this.$get()返回的内容。

    一般情况下,factory和service区别很小。

    如过需要写的service里不需要定义自己的属性,那么我们可以使用factory,代码较为简洁。

  • 相关阅读:
    python-pycharm-django
    CSS
    django邮件
    访问user Model的三种方式
    weblogic升级war包(工作备忘)
    RestfulAPI_ 验证 与授权
    Restful API serialize相关
    scripy login captcha
    linux环境设置和核心命令
    java 调用JIRA api接口
  • 原文地址:https://www.cnblogs.com/perallina/p/6840623.html
Copyright © 2020-2023  润新知