Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non XHR (non-AJAX) Post request from Angular

There is one requirement to use an external service from within our Angular Application. The external service has its own User Interface. So, we have to redirect to the external service using a pure HTTP Post request on the given External Service's URL.

Is there a way to do non-AJAX post call from Angular so that the screen redirects to the external service webpage.

like image 782
Nehal Damania Avatar asked Aug 23 '18 12:08

Nehal Damania


1 Answers

The solution is to dynamically create a form on fly and submit. I created a method in a Service class something like below to make it work. This method was then invoked from component. Created a helper method createHiddenElement as had many more parameters to be posted. Hope this helps someone.

  postToExternalSite(dataToPost: SomeDataClass): void {
    const form = window.document.createElement("form");
    form.setAttribute("method", "post");
    form.setAttribute("action", "https://someexternalUrl/xyz");
    //use _self to redirect in same tab, _blank to open in new tab
    form.setAttribute("target", "_blank"); 

    //Add all the data to be posted as Hidden elements
    form.appendChild(this.createHiddenElement('firstname', dataToPost.firstName));
    form.appendChild(this.createHiddenElement('lastname', dataToPost.lastname));

    window.document.body.appendChild(form);
    form.submit();
  }

  private createHiddenElement(name: string, value: string): HTMLInputElement {
    const hiddenField = document.createElement('input');
    hiddenField.setAttribute('name', name);
    hiddenField.setAttribute('value', value);
    hiddenField.setAttribute('type', 'hidden');
    return hiddenField;
  }
like image 96
Nehal Damania Avatar answered Sep 25 '22 23:09

Nehal Damania