Non XHR (non-AJAX) Post request from Angular

点点圈 提交于 2020-06-09 12:52:46

问题


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.


回答1:


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;
  }


来源:https://stackoverflow.com/questions/51985353/non-xhr-non-ajax-post-request-from-angular

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!