angular中的$http服务(service)解析

来源:互联网 发布:2017中国人工智能排名 编辑:程序博客网 时间:2024/06/08 06:51


1.1. 前述:

ng中的$http用于请求后台数据,类似于js用的ajax和jq中的$.ajax在ng的$http中的方法有            0、$http            1、$http.get            2、$http.head            3、$http.post            4、$http.put            5、$http.delete            6、$http.jsonp            7、$http.patch 用法大相径庭,本文选取几个典型的进行解析。

1.2. $http

基本语法:     $http({         url: ...         mathod: ...      })     在ng中$http方法返回的是一个promise对象。它有一个success方法和一个error方法。        1>在 ng 1.5.8版本中:            $http({                url: ...                mathod: ...            }).success(function(data){})  //请求成功时调用              .error(function(data){})    //请求失败时调用        2>在 ng 1.6.0以上的版本中:             $http({                  url: ...                  mathod: ...              }).then(success,error)         其中success和error分别是请求成功和请求失败时的回调函数

1.2.1. 示例demo:

   var req = {    method: 'POST',    url: 'http://example.com',    headers: {      'Content-Type': undefined    },    data: { test: 'test' }   }   $http(req).then(function(){...}, function(){...});

1.3. $http.get()/post() 用法参照$http(基本相同)

   基本语法:以get为例       $http.get(url).then(success,error);        传入一个url请求的地址,返回一个promise对象,给对象有一个then方法。         then方法的第一个参数是请求成功时的回调函数,第二个参数时请求失败时的回调函数

1.3.1. 示例demo:

 $http.get( url )       .then( function ( info ) {           console.log( info.data );           $scope.restaurants = info.data;       });

1.4. $http.jsonp() 用法参照$http(基本相同)

   基本语法:        语法: $http.jsonp( url ).then( ... )        注意: url 应该带有 callback 参数, 并且参数的值为 JSON_CALLBACK

1.4.1. 示例代码:

  $http.jsonp( 'http://jklib.org/ele/citiesjsonp.ashx?callback=JSON_CALLBACK' )        .success( function ( data ) {            console.log( data );        } );

1.5. jsonp跨域的原理解析(本质)

  • 在‘全局’范围内有一个函数
  • script标签可以下载js文件(字符串)
  • script可以执行下载的脚本

1.5.1. 跨域原理示例demo:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>Document</title>    <script>        var common = {};        common.func = function ( v ) {            console.log( v );        };    </script>    <script src="http://127.0.0.1/jsonptest.js"></script></head><body></body></html>

jsonptest.js 文件 // function func () { // alert( 1 ); // } common.func( { name: '123', age: 123, gender: '123' } );

1.5.1.1.1. 注意:
在  ng 1.6 的版本中需要注意, 请求的路径要配置白名单,例如: .config(['$sceDelegateProvider', function($sceDelegateProvider) {     $sceDelegateProvider.resourceUrlWhitelist([         '**'         // 在 node 平台下引入了 全局通配符         // 使用 * 表示一个目录下任意的文件或文件夹         // 使用 ** 表示任意目录结构下多个文件夹结构         //      /index/index/index.html         //      /*/*/*.html         //      /**/*.html     ]); }])
0 0
原创粉丝点击