Angular 2 Post Form到外部链接

时间:2016-07-14 06:08:29

标签: javascript angularjs angular

我是Angular 2中的新手。它似乎是starnge,但我需要将form发送到外部链接,而且,我需要在发布请求后将用户重定向到此页面...

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

在我通过JQuery提出这样的请求之前:

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

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

    });
</script>

但现在我陷入了困境,不知道如何在Angular 2中做到这一点。我阅读了很多主题,但他们无助。我尝试了window.location.href = '...';,但它仅对Get请求有用,对帖子没用。任何帮助表示赞赏。

更新 我尝试过(服务中):

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

在组件中:

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

我有错误:

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.

在我的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;
}

1 个答案:

答案 0 :(得分:-1)

根据帖子请求的状态代码尝试此操作

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