【问题标题】:Angular reactive forms - prevent refresh on submissionAngular 反应式表单 - 防止提交时刷新
【发布时间】:2020-08-23 00:04:17
【问题描述】:

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

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

}

【问题讨论】:

  • 创建一个服务并存储计数器值,当您需要使用 observable() 从那里获取它时,由于 router.navigate 计数器会重置
  • 很高兴知道它有效.. 不客气 :)

标签: javascript angular angular-reactive-forms


【解决方案1】:

您可以创建一个服务并使用 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']);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 2021-07-02
    相关资源
    最近更新 更多