2

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?

slideshowp2
  • 38,463
  • 29
  • 127
  • 255
Andrew
  • 21
  • 2

1 Answers1

0

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

Naing
  • 53
  • 5
  • I dont think that will work. The reason is this - I need to send info to the new page in order for it to populate with get the data needed. If I do a POST request and then separately redirect, wouldn't the user's browser essentially run a GET request on that other web page? Also, router.navigate wouldn't work here because the next page is part of a different application all together. – Andrew Apr 09 '20 at 15:01