表格在Angular 2.0.1上两次触发ngSubmit

时间:2016-10-19 12:45:11

标签: angular typescript angular2-forms

对于Angular 2.0.1中的任何表单,每当我按下return或单击提交按钮时,ngSubmit输出都会被触发两次。我已在应用程序模块中包含FormsModule

@NgModule({
  imports: [
    BrowserModule,
    HttpModule,
    FormsModule,
    routing
  ],
  declarations: [
    // ...
  ],
  providers: [
    // ...
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

我已尝试关注某些答案(例如this),但自RC6以来disableDeprecatedFormsprovideForms已被删除。我还尝试导入DeprecatedFormsModule,但它似乎也被删除了。

我应该怎么做以防止ngSubmit被解雇两次?

更新:

我并不认为模板在这种情况下会很重要,因为它是一个已知问题,它适用于应用程序中的任何形式,但是这里以其中一个表格为例(剥离了不必要的类和标签):

<form (ngSubmit)="login(user)">
  <input [(ngModel)]="user.username" name="username" type="email" id="username" required>
  <label for="username">Email</label>

  <input [(ngModel)]="user.password" name="password" type="password" id="password" required>
  <label for="password">Password</label>

  <button>
    Submit
  </button>
</form>

1 个答案:

答案 0 :(得分:0)

After some some comments I tried to reproduce the error in a Plunker only to realize that the problem was something else entirely. What was being fired twice was not the ngSubmit, but the HTTP request.

I was subscribing twice to the same http.post(args), what happens is that I need to call .share() so it won't be executed for every subscribe (https://stackoverflow.com/a/37241863/2908285).