简体   繁体   English

Angular 2发布表单到外部链接

[英]Angular 2 Post Form to External Link

I am new in Angular 2. It seems to be starnge, but I need to send form to external link, moreover, I need to redirect user to this page after post request... 我是Angular 2的新用户。这似乎很繁琐,但是我需要将form发送到外部链接,而且,发布请求后,我需要将用户重定向到此页面...

<form id="Form" method="post" action="http//somelink.com" target="TheWindow">
    <input type="hidden" name="linkname" value="someValue" />
</form>

Before I made that request by JQuery like that: 在我通过JQuery发出请求之前,像这样:

<script>
    $( document ).ready(function() {

        $( ".btnUpgrade" ).on( "click", function(){
            window.open('', 'TheWindow');
            document.getElementById('Form').submit();
        });

    });
</script>

But now I'm stuck and no idea how to do that in Angular 2. I read a lot of topics but they been helpless. 但是现在我陷入困境,不知道如何在Angular 2中做到这一点。我读了很多主题,但是他们很无助。 I tried window.location.href = '...'; 我尝试了window.location.href = '...'; but it's good only for Get request and useless for post. 但这仅对获取请求有用,对发布无用。 Any help appreciated. 任何帮助表示赞赏。

UPDATE What I tried(in Service): 更新我尝试过的(在服务中):

submitHiddenForm() {
    var headers = new Headers();
    headers = this._httpClient.createCustomHeader();
    var url = 'http//somelink.com';
    var body = 'linkname=someValue';
    return this.http.post(url, body, headers).map(this.extractData).catch(this.handleError);
}

In component: 在组件中:

submitHiddenForm() {
    this._upgradeService.submitHiddenForm().subscribe (data => {
            window.location.href = 'http://somelink.com'; },
        error => {console.log('Error while redirecting!'); });
}

I have error: 我有错误:

XMLHttpRequest cannot load http://somelink.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

In my POST request I have such Headers: 在我的POST请求中,我有这样的标头:

createCustomHeader(): Headers {
    var headers = new Headers();
    headers.append('Access-Control-Allow-Origin', '*');
    headers.append('Access-Control-Allow-Headers', 'origin, x-requested-with, x-http-method-override, content-type');
    headers.append('Access-Control-Allow-Methods', 'POST');
    headers.append('Access-Control-Allow-Credentials', 'true');
    return headers;
}

try this on the basis of status code of post request 根据发布请求的状态码尝试此操作

this.http.request(new Request(this.requestoptions))
.subscribe(res => {
        if (res[0].status == 201) {
          this.router.navigateByUrl('..URL here..');
        }
        console.log(res[0].json);
      },
      err => {
        console.log(err);
      })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM