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


1.1. 前述:

ng中的$http用于请求后台数据,类似于js用的ajax和jq中的$.ajax
在ng的$http中的方法有0、$http1、$http.get2、$http.head3、$http.post4、$http.put5、$http.delete6、$http.jsonp7、$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:



Document



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]);}])


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部