Currently, I am working on a project using Angular and TypeScript. The goal is to retrieve a list of users from an API and allow for the addition of new users. However, I am struggling with determining how to verify if a user with a specific name already exists in the API, and prevent saving if it does. I attempted to use the find()
method but encountered an error indicating that 'find' was not recognized on that type.
Below is a snippet from 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);
});
}
Here is the HTML fragment:
<button *ngIf="name.valid && number.valid && description.valid" (click)="saveClient()"
class="btn btn-success">Submit</button>
The service.ts file looks like this:
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}`);
}
}
Lastly, the data fragment contains the following information:
"clients": [
{
"id": 1,
"name": "Adams - Yundt",
"number": 5957752672,
"description": "Tacoma"
},
{
"id": 2,
"name": "Crist & Witting",
"number": 6753900414,
"description": "Beaumont"
}
]