Teekam
Teekam

Reputation: 939

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

enter image description here

Upvotes: 0

Views: 374

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71941

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

Upvotes: 1

Related Questions