Angular 2中的HTTP转换请求 [英] HTTP Transform request in Angular 2

查看:79
本文介绍了Angular 2中的HTTP转换请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向我的所有Web请求添加单个参数,以便强制禁用缓存。我要做的就是添加

I am attempting to add a single parameter to all my web requests so that caching is forcibly disabled. All I want to do is add

?v=1535DC9D930 // Current timestamp in hex

到每个请求的结尾。

我在普通的ES5 JS中写这个,但所有文档都在Typescript中,需要一段时间才能转换。到目前为止我有以下内容:

I am writing this in plain ES5 JS, but all the documentation is in Typescript which is taking a little while to convert. I have the following so far:

(function(app) {
    app.CustomHttp = ng.core
        .Class({
            constructor: [ng.http.Http, function(http) {
                console.log(this);
                this.http = http;
            }],
            request: function() {
                return this.http.request.apply(arguments);
            },
            get: function() {
                return this.http.get.apply(arguments);
            },
            post: function() {
                return this.http.post.apply(arguments);
            },
            put: function() {
                return this.http.put.apply(arguments);
            },
            delete: function() {
                return this.http.delete.apply(arguments);
            },
            patch: function() {
                return this.http.patch.apply(arguments);
            },
            head: function() {
                return this.http.head.apply(arguments);
            }
        });
})(window.app || (window.app = {}));

(function(app) {
    document.addEventListener('DOMContentLoaded', function() {
        ng.core.enableProdMode();
        ng.platform.browser.bootstrap(
            app.AppComponent,
            [ng.core.provide(ng.http.Http, { useClass: app.CustomHttp })]
        ).catch(function(error) {
            console.error(error);
        });
    });
})(window.app || (window.app = {}));

该应用程序完全有效,但 console.log(this) CustomHttp 中的code>,当我在浏览器中检查 ng.http.HTTP_PROVIDERS 时它似乎没有使用 CustomHttp 。我也尝试过:

The app fully works, yet the console.log(this) in the CustomHttp never gets called, and when I inspect ng.http.HTTP_PROVIDERS in the browser it doesn't appear to be using CustomHttp. I have also tried:

[ng.http.HTTP_PROVIDERS, ng.core.provide(ng.http.Http, { useClass: app.CustomHttp })]

在我的 boot.js 无济于事。

我确信有一些我遗失的东西,或者我已经大大过度复杂了这一点(它有多难向所有获取请求添加一个参数?)。

I'm sure there is something tiny that I am missing, or that I have massively over complicated this (How hard can it be to add a single parameter to all get requests?).

推荐答案

仅使用ES5拦截HTTP请求并不容易,主要是因为你没有 super 的支持。

Intercepting HTTP requests with ES5 only isn't so easy mainly because you don't have the support of super.

首先创建一个函数来保存请求获取,... ng.http.Http 对象的方法等价 _request _get 。这允许模拟类似 super.get()的内容。否则,在定义自己的方法时,它们将被覆盖(并丢失)。

First create a function to save the request, get, ... methods of the ng.http.Http object into equivalent _request, _get ones. This allows to simulate something like super.get(). Otherwise they will be overriden (and lost) when defining your own methods.

function createHttpClass() {
  var Http = function() {}
  Http.prototype = Object.create(ng.http.Http.prototype);
  Http.prototype._request = Http.prototype.request;
  Http.prototype._get = Http.prototype.get;
  Http.prototype._post = Http.prototype.post;
  Http.prototype._put = Http.prototype.put;
  Http.prototype._delete = Http.prototype.delete;
  Http.prototype._head = Http.prototype.head;
  return Http;
}

然后你可以创建一个自定义 HttpClass 扩展 ng.core.Http 一:

Then you can create a custom HttpClass that extends the ng.core.Http one:

var CustomHttp = ng.core
  .Class({
    constructor: function(_backend, _defaultOptions) {
      this._backend = _backend;
      this._defaultOptions = _defaultOptions;
    },
    extends: createHttpClass(),
    request: function() {
      console.log('request');
      return this._request.apply(this, arguments);
    },
    get: function() {
      console.log('get');
      return this._get.apply(this, arguments);
    },
    (...)
  });

您可以注意到我利用 extends 使用 createHttpClass 函数创建对象的属性。

You can notice that I leverage the extends attribute with the object create using the createHttpClass function.

您最终需要为此<$ c注册提供程序$ c> CustomHttp class:

You need finally to register the provider for this CustomHttpclass:

ng.platform.browser.bootstrap(AppComponent, [
  ng.http.HTTP_PROVIDERS,
  ng.core.provide(ng.http.Http, {
    useFactory: function(backend, defaultOptions) {
      return new CustomHttp(backend, defaultOptions);
    },
    deps: [ng.http.XHRBackend, ng.http.RequestOptions]
  })
]);

这是相应的plunkr: https://plnkr.co/edit/tITkBJcl4a5KVJsB7nAt

Here is the corresponding plunkr: https://plnkr.co/edit/tITkBJcl4a5KVJsB7nAt.

此实现的灵感来自TypeScript。有关详细信息,请参阅此问题:

This implementation is inspired from the TypeScript one. See this question for more details:

  • Angular 2 (Ionic 2): intercept ajax requests

这篇关于Angular 2中的HTTP转换请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆