【发布时间】: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