how to write a simple http intercept?

∥☆過路亽.° 提交于 2019-12-25 05:09:59

问题


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

Thanks in advance

EDIT:

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?


回答1:


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.

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

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


来源:https://stackoverflow.com/questions/22890860/how-to-write-a-simple-http-intercept

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!