6.2 创建Angular服务

  • 6.2.1 使用factory方法自定义服务
  • 6.2.2 使用service方法自定义服务
  • 6.2.3 使用constant和value方法自定义服务

6.2.1 使用factory方法自定义服务

 angular.module('myapp1',[])
        .factory('$outfun',function(){               //服务$outfun  返回一个方法
            return {
                str:function(n){
                        return n;
                }
            }
        })
        .factory('$outarr',function(){            //服务$outarr 返回一个数组
            return ['张三','王五','李四'];
        })
        .controller('contr',function($scope,$outfun,$outarr){
            $scope.str = function(n){
                return $outfun.str(n);
            }

            $scope.arr = function(n){
                return $outarr[n];
            }
        })

6.2.2 使用service方法自定义服务

angular.module('myapp',[])
      .service('$student',function(){        //service方法创建服务$student,可以返回构造函数,
          this.name = "张桂芳";              //能通过this方法添加属性和方法
          this.email = "[email protected]";
          this.say = function(){
              return "hello";
          }
      })
      .controller('contro',function($scope,$student){ // 通过依赖注入添加$student服务,
          $scope.name = $student.name;   //注入过程中会自动检测到时service,自动通过new实例化服务
          $scope.email = $student.email;
          $scope.say = function(){
              $scope.title = $student.say();
          }
      })
    //注意:
    //    1. 通过factory方法创建的服务,可以使用service方法来代替
    //    2. 通过service方法创建的服务,
    //             1)需要将service方法中的回调函数单独创建为一个自定义的函数
    //             2)使用new实例化

6.2.3 使用constant和value方法自定义服务

<!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>6.2.3使用constant和value方法自定义服务</title>
    </head>
    <body>
          <div ng-app = "myapp" ng-controller="contro">
              <div>图书ISBN号:{{book}}</div>
              <div>美元兑换价:{{usd}}</div>
          </div>

      <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
      <script>

          angular.module('myapp',[])
          .constant('$ISBN',{      //constant创建服务$ISBN
              book: "7987986867"
          })
          .value('$rate',{         //value创建服务$rate
              usd: 614.28
          })
          .controller('contro',function($scope,$ISBN,$rate){    //控制器注入服务$ISBN、$rate
              var n = 600;
              angular.extend($rate,{usd : n});   // angular.extend方法对服务对象中的常量进行重置
              $scope.book = $ISBN.book;
              $scope.usd = $rate.usd;
          })

          //使用constant和value方法自定义服务,常用于返回常量,并在注入控制器后,都可以通过angular.extend方法进行重置
          //区别:constant方法创建的常量可以被注入配置函数(config),常用于创建配置数据
          //      value则不行,常用于创建对象和函数。
      </script>
  </body>
  </html>

注意

1.使用constant和value方法自定义服务,常用于返回常量,并在注入控制器后,都可以通过angular.extend方法进行重置

2.区别:constant方法创建的常量可以被注入配置函数(config),常用于创建配置数据,value则不行,常用于创建对象和函数。

results matching ""

    No results matching ""