AngularJs学习笔记-第三章-服务(service)

1,http
http是angular通过浏览器XMPHttpRequest或者JSONP与远程服务器通信的一个核心服务.
这个demo主要描述http通过不同的方式获取json数据.

<!DOCTYPE html>
<html ng-app="app">
<head>
    <meta Content-Type="html/text;charset=UTF-8">
    <title>http demo</title>
</head>
<body>


<div ng-controller="ctrl">
  <select ng-model="method">
    <option>GET</option>
    <option>JSONP</option>
  </select>
  <input type="text" ng-model="url" size="80" aria-label="URL" />
  <button id="fetchbtn" ng-click="fetch()">获取</button><br>
  <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">获取GEThttp-hello.html</button>
  <button id="samplejsonpbtn"
    ng-click="updateModel('JSONP',
                  'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
    Sample JSONP
  </button>
  <button id="invalidjsonpbtn"
    ng-click="updateModel('JSONP', 'www.baidu.com')">
    <!--https://angularjs.org/doesntexist&callback=JSON_CALLBACK-->
      Invalid JSONP
    </button>
  <pre>http status code: {{status}}</pre>
  <pre>http response data: {{data}}</pre>
</div>


</body>
<script src="js2/angular.js"></script>
<script src="js/submit.js"></script>

js
var APP = angular.module('app', [])
    APP.controller('ctrl', ['$scope', '$http', '$templateCache',
  function($scope, $http, $templateCache) {//JSONP supports only the GET request method. There are significant security implications and risks associated to using JSONP; unless you have no choice, CORS is usually the better choice.
    $scope.method = 'GET';
    $scope.url = 'http-hello.html';
    $scope.fetch = function() {
      $scope.code = null;
      $scope.response = null;

      $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
        success(function(data, status) {
          $scope.status = status;
          $scope.data = data;
        }).
        error(function(data, status) {
          $scope.data = data || "Request failed";
          $scope.status = status;
      });
    };
    $scope.updateModel = function(method, url) {
     $scope.method = method;
     $scope.url = url;
    };
  }]);

页面显示结果:
《AngularJs学习笔记-第三章-服务(service)》
2,怎样利用http实现前后台交互
下面的demo是利用http请求后台的数据,实现前后台交互

<!doctype html>
<html ng-app="app">
  <head>
    <title>demo</title>
    <meta Content-Type="html/text;charset=utf-8">
  </head>
  <body ng-controller="ctrl">
    <div>
       <ul>
          <li ng-repeat="user in users">
             {{user.name}}
          </li>
       </ul>
    </div>
  </body>
  <script src="framework/js/angular.min.js"></script>
  <script src="js/demo.js"></script>
</html>
js
var APP = angular.module('app',[])
    APP.controller('ctrl',['$scope','$http',function($scope,$http){
        $http({
            method:'GET',
            url:'data/data.json'//请求后台url地址
        }).success(function(data,status,headers,config){//promise 形式
            console.log("success...")
            console.log(data)
            $scope.users=data//拿到数据直接赋值
        }).error(function(data,status,headers,config){
            console.log("error...")
        })
    }])

data.json//来自后台的json数据
[{"name":"mike"},
{"name":"tom"},
{"name":"make"}
]

利用最新的firefox浏览器来展示如下页面:
《AngularJs学习笔记-第三章-服务(service)》
2,service
-service都是单例,在一个应用里面不管多么复杂,这有一个service实例。
-service 由$injector负责实例化,也就是说不需要自己去new,而是injector帮助注入实例化,比如说:app.controller(“ctrl”,[“service”]),也就是依赖注入的机制注入service。
-service在整个应用的生命周期中都是存在的,可以像$scope一样用来共享数据的。
-自定义的service需要写在内置的service后面。
-内置的service的命名以$符号开头,自定义的service应该避免。
Service,provider,Factory本质上都是provider
provider模式(设计模式)是‘策略模式’+‘抽象工厂模式’的混合体
http://www.zhex.me/blog/2013/08/03/provider-factory-and-service-in-ang…

    原文作者:MichaelDuan
    原文地址: https://segmentfault.com/a/1190000003007026
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞