I'm making a site that has a form that needs to do a POST to an external payment provider. However, I need to go through my component's code to check if the user is authenticated first. If not, I need to go through my webapi to update a value. Once the response is received, I can continue with the POST to the external URL. My code look like this:
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())
}
}
If this.loggedIn
is true, the POST works correctly. It's only when I need to call the cartService that the form.submit isn't working. Sometimes, the console shows an error, "object does not contain a method submit()", other times, I get nothing in the console....it just isn't working.
Here is the opening form tag:
<form #cartForm="ngForm" (ngSubmit)="onSubmit(cartForm)" method="post" [action]="cart.paymentUrl" >
Any help would be appreciated.
EDIT Here is the markup for my submit button, as requested:
<button type="submit">CHECKOUT</button>
The ngForm
being sent to your event handler does not have a .submit()
method, so you'll need to get the underlying form
from either ngForm
or the event
so you can use its .submit()
method.
For this example, I used the event
.
Markup
<!-- 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();
})
}
}
I stripped it down a bit, but here is a Working Plunker ("Working" as in, you'll notice the failed POST -- after 1 second -- in console
to www.google.com due to cross-domain issues.)