zoukankan      html  css  js  c++  java
  • ng 自定义服务

    服务的本质是对象。

    创建服务的常见方式:
    factory(返回对象) service (方法、属性)constant(常量服务) value(变量服务)


    1、factory
    app.factory('服务名称',function(){
    return {
    key:value
    }
    })

    2、service方法
    app.service('服务名称',function(){
    //构造函数
    this.name = 'zhangsan';
    this.speak = function(){}

    })

    3、constant value
    app.constant('服务名称',{})
    app.value('服务名称',{})

    <!DOCTYPE html>
    <html ng-app="myApp">
    <head lang="en">
      <meta charset="UTF-8">
      <script src="js/angular.js"></script>
      <title></title>
    </head>
    <body>
    <div ng-controller="myCtrl">
        <button ng-click="handleClick()">
          clickMe
        </button>
    </div>
    <script>
      var app = angular.module('myApp', ['ng']);
    
      //通过factory自定义服务
      app.factory('$output', function () {
        return {
          print: function (str) {
            //比较复杂的业务逻辑
            console.log(str);
          }
        }
      });
    
      app.controller('myCtrl',
        function ($scope,$output) {
          $scope.handleClick = function () {
            $output.print('Hello Service');
          }
        })
    </script>
    </body>
    </html>

    2.

    <!DOCTYPE html>
    <html ng-app="myApp">
    <head lang="en">
      <meta charset="UTF-8">
      <script src="js/angular.js"></script>
      <title></title>
    </head>
    <body>
    <div ng-controller="myCtrl">
    
    </div>
    <script>
      var app = angular.module('myApp', ['ng']);
    
      //通过service方法创建服务
      app.service('$student', function () {
        //构造函数
        this.name = 'lucy';
        this.study = function () {
          console.log('正在学习');
        }
      });
    
      app.controller('myCtrl',
        function ($scope,$student) {
          //读取服务中的属性
          console.log("服务中name属性对应的值为"+$student.name);
          //调用服务中的方法
          $student.study();
        })
    </script>
    </body>
    </html>
  • 相关阅读:
    hystrix总结之缓存
    python3列表
    hystrix总结之多返回值命令
    hystrix总结之限流
    hystrix(5) 延时检测
    redis-start
    设计模式-4建造者模式
    设计模式-3原型模式
    设计模式-2工厂设计模式
    设计模式-七大设计原则
  • 原文地址:https://www.cnblogs.com/web-fusheng/p/6958954.html
Copyright © 2011-2022 走看看