Angular 表单不会发布到外部 URL

问题描述 投票:0回答:2

我正在创建一个网站,该网站的表单需要向外部支付提供商进行 POST 操作。但是,我需要检查组件的代码来检查用户是否首先经过身份验证。如果没有,我需要通过我的 webapi 来更新值。收到响应后,我可以继续 POST 到外部 URL。我的代码如下所示:

 onSubmit(form: any): void {  
         //for anonymous orders, we need to store the email before we send the form
         if(this.loggedIn){
            form.submit(); 
         }
         else{
             this.cartService.updateUserEmail(this.cart.id, this.email)
                             .subscribe(() => form.submit())
         }
  }

如果

this.loggedIn
为 true,则 POST 工作正常。只有当我需要调用 cartService 时, form.submit 才不起作用。有时,控制台会显示错误,“对象不包含方法submit()”,其他时候,我在控制台中什么也得不到......它只是不起作用。

这是打开表单标签:

<form #cartForm="ngForm" (ngSubmit)="onSubmit(cartForm)" method="post" [action]="cart.paymentUrl" >

如有任何帮助,我们将不胜感激。

编辑 这是我的提交按钮的标记,根据要求:

<button type="submit">CHECKOUT</button>
html angular angular2-forms
2个回答
11
投票

发送到事件处理程序的

ngForm
没有
.submit()
方法,因此您需要从
form
ngForm
获取底层
event
,以便您可以使用其
.submit()
方法。

在此示例中,我使用了

event

标记

<!-- Note that I added the $event to the handler -->    
<form #cartForm="ngForm" (ngSubmit)="onSubmit(cartForm, $event)" method="post" [action]="cart.paymentUrl" >

TS

onSubmit(form: any, e: any): void {  
     //Note that I added 'e' and calling the event target's .submit()
     if(this.loggedIn){
        e.target.submit();
     }
     else{
         this.cartService.updateUserEmail(this.cart.id, this.email)
            .subscribe(() => {
                e.target.submit();
            })
     }
}

我把它精简了一点,但这里有一个 Working Plunker(“工作中”,你会注意到 1 秒后,在

console
到 www.google.com 由于交叉-域名问题。)


0
投票

您可以尝试这种方式并告诉我是否可以解决您的问题吗?

模板:

<form (ngSubmit)="onSubmit()" #cartForm ="ngForm" >...</form>

组件:

@ViewChild('cartForm') cartForm: NgForm;

onSubmit() {  
         //for anonymous orders, we need to store the email before we send the form
         if(this.loggedIn){
            this.SomeService.create(this.cartForm.value, this.cart)
         }
         else{
             this.cartService.updateUserEmail(this.cart.id, this.email)
                             .subscribe(() => 
                                this.someService.create(this.cartForm.value, this.cart)
                             )
         }
  }

一些服务:

create(yourModel, cart): Observable<yourModel> {
    return this.http
      .post(cart.paymentUrl, JSON.stringify(yourModel), {headers: this.headers}) 
      .map(res => res.json())
      .catch(//handle errors);
  }
© www.soinside.com 2019 - 2024. All rights reserved.