如何写一个简单的http拦截? [英] how to write a simple http intercept?

查看:29
本文介绍了如何写一个简单的http拦截?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释以下内容有什么问题吗?

Can somebody explain what is wrong with the following?

void main() {
  var intercept = new HttpInterceptor();
  intercept.response = (HttpResponse response) => print('we have a response');
  Injector injector = ngBootstrap(module: new MyModule());
  var interceptors = injector.get(HttpInterceptors);
  interceptors.add(intercept);
}

提前致谢

这是我如何执行 http 请求(从指令内部):

And here is how I do an http request (from inside a directive):

@NgDirective(
  selector: '.my-selector')
class MyDirective implements NgAttachAware {
  @NgOneWay('id')
  String id;
  Element self;
  MyDirective(Element el) {
    self = el;
  }
  void attach() {
    final String _urlBase = 'http://www.some-site.com/';
    HttpRequest req = new HttpRequest();
    req.open('GET', _urlBase + id);
    req.overrideMimeType('text\/plain; charset=x-user-defined');
    req.onLoadEnd.listen((e) {
      if (req.status == 200) {
        // do something useful
      } else {
        print('download failed');
      }
    });
    req.send();
  }
}

请求成功返回,但拦截器永远不会触发.为什么?

Requests return successfully but the interceptor never fires. Why?

推荐答案

您必须使用 AngularDart 内置服务Http",而不是 dart:html HttpRequest 类.HttpInterceptors 仅在使用包装 HttpRequest 类的服务时才起作用.

You must use the AngularDart built-in service "Http" and not the dart:html HttpRequest class. The HttpInterceptors only work on when using that service which wraps the HttpRequest class.

换句话说,在指令的构造函数中注入 Http:

In other words, inject Http in the directive´s constructor:

MyDirective(Element el, Http http) {
  self = el;
  this._http = http;
}

这篇关于如何写一个简单的http拦截?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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