有人可以解释以下问题吗?
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请求(来自指令内部):
@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();
}
}
请求成功返回,但拦截器永远不会触发。为什么呢?
答案 0 :(得分:1)
您必须使用AngularDart内置服务“Http”而不是dart:html HttpRequest类。 HttpInterceptors仅在使用包装HttpRequest类的服务时才起作用。
换句话说,在指令的构造函数中注入Http:
MyDirective(Element el, Http http) {
self = el;
this._http = http;
}