0

So I am doing the project with angular and typescript where I get list of users from API and simply add new users. I don't know how to check if the user with given name exists in my API and disable saving if it does. I tried with find() but I get the error that 'find' does not exist on that type.

Here is fragment of my .ts file:

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 fragment:

<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}`);
  }


}

And data fragment:

"clients": [
    {
      "id": 1,
      "name": "Adams - Yundt",
      "number": 5957752672,
      "description": "Tacoma"
    },
    {
      "id": 2,
      "name": "Crist & Witting",
      "number": 6753900414,
      "description": "Beaumont"
    }
]
qqtf
  • 632
  • 6
  • 17
caramel
  • 60
  • 8
  • 2
    Without knowing the details of your API, no one can answer your question. – Nathaniel Johnson Jul 07 '21 at 20:07
  • You would need to write an async validator on your name field to get a count of users that match that name. If the count is > 0, it's a duplicate. – Brandon Taylor Jul 07 '21 at 20:58
  • @Brandon I'm not sure how to do this with template driven forms – caramel Jul 07 '21 at 21:29
  • @caramel I would highly recommend converting to reactive forms. You're going to get a lot more control. Template driven forms are ok for something quick and dirty, but not for anything complex. Just my opinion from using Angular for 5 1/2 years. – Brandon Taylor Jul 07 '21 at 21:32
  • @Brandon okay, thank you, I will use reactive forms in my next projects but here I have to leave it as it is :) – caramel Jul 07 '21 at 21:42
  • Good luck with that. This answer might help you out: https://stackoverflow.com/questions/36235446/angular2-template-driven-async-validator – Brandon Taylor Jul 07 '21 at 21:44

1 Answers1

1

In angular you do validation on entered form values, not a db check, that's for the API. Meaning, if someone tries to make a duplicate, does entered values, from a form standpoint are correct. There should be no logic preventing the user to submit, neither to send that data to the API.

It's in the API that you match received data with current db-values. We don't know anything of your API (=> incomplete question), so this can't be discussed here.

The check is executed, you send back an error-message. I don't think your angular apiclient is catching that. Maybe try this (double check syntax like ({},; ):

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

and consequently do something useful with

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

like (and there are a kzillion possibilities here)

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

with

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

Take care & good luck. Let us know if this doesn't work for you.

qqtf
  • 632
  • 6
  • 17