且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 angular dart 上设置全局 Http 请求标头

更新时间:2022-03-23 09:34:05

(我认为)我得到了它:

(I think) I got it working with:

@Injectable()
class MyDefaultHeaders extends HttpDefaultHeaders {
  @override
  setHeaders(Map<String, String> headers, String method) {
    super.setHeaders(headers, method);
    //if(method.toUpperCase() == 'POST') {
    headers['X-Requested-With'] = 'XMLHttpRequest';
    //}
  }
}


@NgComponent(selector: 'my-comp', publishAs: 'ctrl', template:
    '<div>My component</div>')
class MyComponent {
  Http http;
  MyComponent(this.http) {
    //http.request('http://www.google.com/');
    var h = http;
        // debugger didn't show http so I filed https://code.google.com/p/dart/issues/detail?id=17486

    Map m = {};
    http.defaults.headers.setHeaders(m, 'GET');
    print(m);
    // prints:
    // {Accept: application/json, text/plain, */*, X-Requested-With: XMLHttpRequest}

  }
}


class MyAppModule extends Module {
  MyAppModule() {

    type(MyComponent);

    type(HttpDefaultHeaders, implementedBy: MyDefaultHeaders);

    init.createParser(this);
  }
}

我无法检查 http 以验证标头,因为调试器没有向我显示该字段,但如评论中所述当我应用 headers.setHeadersMyComponent 中做一个映射时,我得到了我的自定义标头(这就是 Httpheaders代码>)我使用了 DI 0.0.33Angular 0.9.9

I couldn't examine http to verify the headers because the debugger didn't show me the field but as stated in the comment when I apply headers.setHeaders do a map inside MyComponent I get my custom header (this is what Http does with headers) I used DI 0.0.33, Angular 0.9.9