来自Angular的非XHR(非AJAX)发布请求 [英] Non XHR (non-AJAX) Post request from Angular

查看:103
本文介绍了来自Angular的非XHR(非AJAX)发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular应用程序中使用外部服务是一项要求.外部服务具有其自己的用户界面.因此,我们必须使用给定外部服务URL上的纯HTTP Post请求重定向到外部服务.

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.

是否可以通过Angular进行非AJAX后期调用,以便将屏幕重定向到外部服务网页.

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

推荐答案

解决方案是动态创建表单并提交.我在Service类中创建了一个类似于以下内容的方法,以使其正常工作.然后从组件调用此方法.创建了一个辅助方法createHiddenElement,其中有许多要发布的参数.希望这对某人有帮助.

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

这篇关于来自Angular的非XHR(非AJAX)发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆