微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AngularJS – 如何对所有jsons请求进行deflate和编码/解码到base64?

让我说我的角度应用程序周围有几个$资源和一些$http:
myApp.factory('Note',function($resource) {

  return $resource('http://',{id: '@id'},{ 'index': { method: 'GET',isArray: true },'update': { method: 'PUT'},});
  });

与控制器

myApp.controller('NotesController',function NotesController($scope,Note,AuthenticationService) {

$scope.notes = Note.index({},function(data){
    console.log('success,got data: ',data);
    $scope.response = "yoy!"
  },function(err){
    console.log('error,err);
    $scope.response = "yay!"
  }); 
});

并且一些请求由$http直接进行,如身份验证

var request = $http.post('http://',{email: email,password: password});

在发出实际请求/接收响应之前,我可以在何处以及如何判断角度以对JSON进行收缩和编码/解码?

我想我将外部库包装为deflate并编码/解码到工厂.然后这个工厂将被注入?
喜欢$httpBackend?

您应该查看$http服务的请求/响应转换器: http://docs.angularjs.org/api/ng.$http

请求/响应转换器只是在将内容发送/返回给调用者之前可以调用函数.您可以全局(针对所有请求/响应)以及每个请求基础指定转换函数

To override these transformation locally,specify transform functions
as transformRequest and/or transformResponse properties of the config
object. To globally override the default transforms,override the
$httpProvider.defaults.transformRequest and
$httpProvider.defaults.transformResponse properties of the
$httpProvider.

要定义全局请求/响应转换器,可以沿着这些行编写代码(它更像伪代码,不适用于所有浏览器,请参阅下面有关Base64的说明):

angular.module('sample',[],function($httpProvider) {

    $httpProvider.defaults.transformRequest = function(data,headersGetter) {
        return btoa(JSON.stringify(data));
    };

    $httpProvider.defaults.transformResponse = function(data,headersGetter) {
        return JSON.parse(atob(data));
    };

})

当然,您的转换代码可能更复杂,并且取决于请求/响应标头,但总体思路就在这里. jsfiddle代码(检查控制台以查看请求被转换,您需要使用Mozilla或WebKit浏览器):http://jsfiddle.net/Ydt5j/

对于从/到Base64的实际转换,请检查此问题:How can you encode a string to Base64 in JavaScript?

原文地址:https://www.jb51.cc/angularjs/142052.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐