Angular 8 - POST + Redirect exactly like submitting HTML <form>, but without using DOM

Viewed 1980

There's a lot of questions like this but none of them quite get it. The old functionality I need to replicate creates a form using angular JS, appends it, then submits. It makes a POST request with data & redirects at the same time. I don't plan to run it literally like that... If I literally ran a Post request via HttpClient, and then redirected to the URL, the end-user would essentially just make a GET request to that URL. Therefore, this has to be done via forms somehow.

A service runs this function, so there is no template file associated directly.

We have old AngularJS code which we are replicating. The old code creates a form element, adds content, appends it directly to the DOM, then submits it:

var input = angular.element('<form>', {
  action: '/someUrl.go',
  method: 'POST'
});
form.append(angular.element('<input>', {
  value: someValue,
  name: someKey
}));
form.appendTo('body').submit();

I am looking for a better way to do the same thing in Angular 8. I know I could just use Javascript and DOM manipulation, but there has got to be a better way.

It would not feel right to me to use Javascript along these lines:

let form = document.createElement('form');
form.action = '/someUrl.go';
form.method = 'POST';
let input = document.createElement('input');
input.name = "someKey";
input.value = "someValue";
input.type="hidden";
form.appendChild(input);
document.body.appendChild(form);
form.submit();

I did go through the answers on this topic (JavaScript post request like a form submit) but they're still DOM manipulation, javascript or jQuery. How can I do this "correctly" using typescript & angular's toolbox?

2 Answers

  var form = document.createElement("form");
   form.method = "POST";
   form.action = "https://somewebsite.comd/somepage";
   form.style.display = 'none';
  
   // form['Content-Type'] =  'application/x-www-form-urlencoded';
   // form['Accept'] = 'application/json';
   // above attributes are not valid


  var account_number = document.createElement("input");
   account_number.value='xxxxxxxxx';
   account_number.name='account_number';
   form.appendChild(account_number);

 document.body.appendChild(form);
 form.submit();                       // will submit the form

Just make a post request using HttpClient and for redirecting, use Router.navigate(['/xxx']) inside subscribe block of post request.

Related