angular中的$http服务(service)解析
2017-04-02 22:47
676 查看
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 ]); }])
相关文章推荐
- angular服务$http 解析json文件
- angular自定义服务factory和service源码解析
- Android 系统服务的注册以及 getService() 方法源码解析
- Android Service完全解析,关于服务你所需知道的一切(下)
- Android Service完全解析,关于服务你所需知道的一切(上)
- Android Service完全解析,关于服务你所需知道的一切(上)
- Android源码解析之新进程中启动自定义服务过程(startService)的原理分析
- Android Service完全解析,关于服务你所需知道的一切(上)
- Android Service完全解析,关于服务你所需知道的一切
- Android Service完全解析,关于服务你所需知道的一切
- Angular2 http服务
- Angular2 http服务
- Android Service完全解析,关于服务你所需知道的一切
- Android Service完全解析,关于服务你所需知道的一切(下) (转载)
- Android Service完全解析,关于服务你所需知道的一切(下)
- 通过AngularJS实现前端与后台的数据对接——服务(service,$http)
- angular服务——$http
- 服务(Service)全解析(四)--AIDL
- Angular2 Service实现简单音乐播放器服务
- Android Service完全解析,关于服务你所需知道的一切(下)