5

I am using angular 4 for one of my projects and i have a method which creates a form element dynamically and submits it

postToUrl(path, params, method) {
        method = method || 'post';
        let form = document.createElement('form');
        form.setAttribute('method', method);
        form.setAttribute('action', path);
        for (let key in params) {
            if (params && params.hasOwnProperty(key)) {
                let hiddenField = document.createElement('input');
                hiddenField.setAttribute('type', 'hidden');
                hiddenField.setAttribute('name', key);
                hiddenField.setAttribute('value', params[key]);
                form.appendChild(hiddenField);
            }
        }
        document.body.appendChild(form);
        form.submit();
        setTimeout(() => {
            document.body.removeChild(form);
        }, 2000);
    }

What i want to do is set a custom header to the request so that i can attach all the headers required by the server. Is there any way i can write a common interceptor for this so that i don't have to repeat the lines. Please help. Any help is appreciated.

Vikhyath Maiya
  • 3,122
  • 3
  • 34
  • 68
  • Why would you be doing posts that way? Even if you weren't using angular – David Apr 22 '18 at 20:36
  • This post call is to download a huge file. I want to give the control to browser so that i dont hav to store in browser cache when the result comes. If i use angular post, i might have to end up using filesaver or streamsaver and the file will be stored in memory till its downloaded .Atleast thats what i thought.. – Vikhyath Maiya Apr 23 '18 at 02:57
  • I have similar problem, in which I want to add custom header, any ideas? – Siddhesh Kulkarni Jun 16 '20 at 07:15

1 Answers1

0

I can't understand your requirement completely but if you are using angular then you can add and intercept headers (client side) via HTTPClient module

Here is another answer that might help you.

https://stackoverflow.com/a/47393331/6841216

ElvenStar
  • 36
  • 3
  • 1
    The post call is to download a huge file. I want to give the control to browser so that i dont hav to store in browser cache when the result comes. If i use angular post, i might have to end up using filesaver or streamsaver and the file will be stored in memory till its downloaded .Atleast thats what i thought. – Vikhyath Maiya Apr 23 '18 at 02:58