简体   繁体   中英

How to set headers in Angular2 by extending BrowserXhr?

I am setting header for Angular 2 app. Here is my code:

 @Injectable()
    export class browserXhr extends BrowserXhr {
      constructor() {}
      build(): any {
        let xhr:XMLHttpRequest = super.build();
         xhr.setRequestHeader('X-Custom-Header', 'value');
        return <any>(xhr);
      }
    }

As I run it gives error

在此处输入图片说明

Without you posting the error, it's just guess work as to what's going wrong. But probably you should add a super() call inside the constructor. Another point of interest is the almost same name of the class, besides the capital. It's common practice to have your class name in PascalCase :

 @Injectable()
 export class MyBrowserXhr extends BrowserXhr {
      constructor() {
         super(); //<-- here
      }

      build(): XMLHttpRequest {
        let xhr:XMLHttpRequest = <XMLHttpRequest>super.build();
        xhr.open(method, url, async?, user?, password?); //fill in the correct details
        xhr.setRequestHeader('X-Custom-Header', 'value');
        return xhr;
      }
 }

After you posted your error, it is obvious what you have to do first. Before setting the request headers, you have to open the request using the open method:

xhr.open(method, url, async?, user?, password?);

After you call this method, you will be able to set your request headers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM