角反应形式-防止刷新提交

时间:2020-08-22 14:14:34

标签: javascript angular angular-reactive-forms

我正在使用反应形式,我有一个简单的形式来添加产品。 这是产品界面:

export interface Product {
    id: number,
    name: string,
    storeName: string,
    price: number,
    isRecieved: boolean,
    deliveryDate: Date
}

每次用户单击“添加按钮”时,都会提交表单。由于每次将ID添加到提交的产品时,我都不想刷新页面,因此可以使idCounter变量保持更新。尽管我在提交后添加了event.preventDefault(),但idCounter转向了它的起始值,因此我猜测页面正在更新。我该如何预防?

<form [formGroup]="addProductForm" (ngSubmit)="onSubmit($event)">
<div>More inputs</div>
<button type="submit" mat-button color="accent" >Add Product</button>
countId:数字= 1;
onSubmit(e) {
e.preventDefault();
if (this.addProductForm.valid) {
  this.addProductForm.value.id = this.countId;
  console.log(this.addProductForm.value)
  this.addProductForm.value.isRecieved = false;
  this.store.dispatch(addProductToList(this.addProductForm.value));
  this.countId++;
  this.addProductForm.reset(this.addProductForm)
  this.router.navigate(['/products']);
}

}

1 个答案:

答案 0 :(得分:0)

您可以如下所示创建服务并使用BehaviorSubject,并且每次在ngOnInit()上都可以通过asObservable()获取值:

服务:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class UserService {
    private counterId: BehaviorSubject<number> = new BehaviorSubject(0);
    counterIdStatus = this.counterId.asObservable();

    updateCounterId(id) {
    this.counterId.next(id);
  }
}

Component.ts:

constructor(
    private userService: UserService,
  ) { }

.....

ngOnInit(): void {
  this.userService.counterIdStatus.subscribe(data => this.countId = data);
} 

onSubmit() {
if (this.addProductForm.valid) {
  this.addProductForm.value.id = this.countId;
  console.log(this.addProductForm.value)
  this.addProductForm.value.isRecieved = false;
  this.store.dispatch(addProductToList(this.addProductForm.value));
  this.countId++;
  this.userService.updateCounterId(this.countId);
  this.addProductForm.reset(this.addProductForm)
  this.router.navigate(['/products']);
}