【问题标题】:Angular forms: how to perform a check for a duplicate database-entry?Angular 表单:如何检查重复的数据库条目?
【发布时间】:2021-09-18 08:51:01
【问题描述】:

所以我正在使用 angular 和 typescript 进行项目,我从 API 获取用户列表并简单地添加新用户。我不知道如何检查给定名称的用户是否存在于我的 API 中,如果存在则禁用保存。我尝试使用find(),但我收到错误提示“find”在该类型上不存在。

这是我的 .ts 文件的片段:

export class AddClientComponent implements OnInit {
  client = {
    name: '',
    number: '',
    description: ''

  };
  submitted = false;


  constructor(private clientService: ClientService) { }

  ngOnInit(): void {
  }
  saveClient(): void {

    const data = {
      name: this.client.name,
      number: this.client.number,
      description: this.client.description

    };
    this.clientService.create(data)
      .subscribe(
        response => {
          console.log(response);
          this.submitted = true;
        },
        error => {
          console.log(error);
        });
  }

html片段:

<button *ngIf="name.valid && number.valid && description.valid" (click)="saveClient()"
        class="btn btn-success">Submit</button>

service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

const baseUrl = 'http://localhost:3000/clients';

@Injectable({
  providedIn: 'root'
})
export class ClientService {

  constructor(private http: HttpClient) { }

  getAll(): Observable<any> {
    return this.http.get(baseUrl);
  }

  get(id: any): Observable<any> {
    return this.http.get(`${baseUrl}/${id}`);
  }

  create(data: any): Observable<any> {
    return this.http.post(baseUrl, data);
  }

  update(id: any, data: any): Observable<any> {
    return this.http.put(`${baseUrl}/${id}`, data);
  }

  delete(id: any): Observable<any> {
    return this.http.delete(`${baseUrl}/${id}`);
  }


}

和数据片段:

"clients": [
    {
      "id": 1,
      "name": "Adams - Yundt",
      "number": 5957752672,
      "description": "Tacoma"
    },
    {
      "id": 2,
      "name": "Crist & Witting",
      "number": 6753900414,
      "description": "Beaumont"
    }
]

【问题讨论】:

  • 在不知道你的 API 细节的情况下,没有人可以回答你的问题。
  • @NathanielJohnson 我编辑了我的问题
  • 您需要在您的名称字段上编写一个异步验证器,以获取与该名称匹配的用户计数。如果计数 > 0,则为重复。
  • @Brandon 我不确定如何使用模板驱动的表单来做到这一点
  • @caramel 我强烈建议转换为反应形式。你会得到更多的控制权。模板驱动的表单适用于快速和肮脏的东西,但不适用于复杂的东西。只是我使用 Angular 5 1/2 年的看法。

标签: angular typescript validation


【解决方案1】:

在 Angular 中,您对输入的表单值进行验证,而不是数据库检查,这是针对 API 的。这意味着,如果有人试图复制,从表单的角度来看,输入的值是否正确。不应该有逻辑阻止用户提交,也不应该将数据发送到 API。

您可以在 API 中将接收到的数据与当前 db-values 进行匹配。我们对您的 API 一无所知(=> 不完整的问题),因此无法在此处讨论。

检查被执行,你发回一个错误信息。 我不认为你的 angular apiclient 能抓住这一点。也许试试这个(双重检查语法,如 ({},; ):

create(data: any): Observable<any> {
    return this.http.post(baseUrl, data)
                .pipe(map(createResponse => createResponse));
  }

然后做一些有用的事情

 error => {
          console.log(error);
        });

喜欢(这里有无数种可能性)

 async (error: HttpErrorResponse) => {
                    const receivedError = JSON.parse(await error.error.text());
                    const message: string = "myErrorMessageTitle";
                    this.toastr.error(receivedError, message);
                });

import { ToastrService } from 'ngx-toastr';
constructor(private toastr: ToastrService) {}

保重,祝你好运。如果这对您不起作用,请告诉我们。

【讨论】:

  • 非常感谢您的回答!
猜你喜欢
  • 1970-01-01
  • 2010-09-30
  • 2014-03-16
  • 2012-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
相关资源
最近更新 更多