步骤
1、cities.service.ts
import { Injectable } from '@angular/core';
import { City } from "../models/city";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable } from "rxjs";
const API_BASE_URL: string = "https://localhost:7173/api/";
@Injectable({
providedIn: 'root'
})
export class CitiesService {
cities: City[] = [];
constructor(private httpClient: HttpClient) {
}
public getCities(): Observable<City[]> {
let headers = new HttpHeaders();
headers = headers.append("Authorization", "Bearer mytoken");
return this.httpClient.get<City[]>(`${API_BASE_URL}v1/cities`, { headers: headers })
}
public postCity(city: City): Observable<City> {
let headers = new HttpHeaders();
headers = headers.append("Authorization", "Bearer mytoken");
return this.httpClient.post<City>(`${API_BASE_URL}v1/cities`, city, { headers: headers })
}
public putCity(city: City): Observable<string> {
let headers = new HttpHeaders();
headers = headers.append("Authorization", "Bearer mytoken");
return this.httpClient.put<string>(`${API_BASE_URL}v1/cities/${city.cityID}`, city, { headers: headers })
}
public deleteCity(cityID: string | null): Observable<string> {
let headers = new HttpHeaders();
headers = headers.append("Authorization", "Bearer mytoken");
return this.httpClient.delete<string>(`${API_BASE_URL}v1/cities/${cityID}`, { headers: headers })
}
}
2、cities.component.html
<h2>Cities</h2>
<div class="flex">
<div class="flex-1 w-50">
<div class="table-container">
<table class="table w-100" [formGroup]="putCityForm">
<thead>
<tr>
<th>#</th>
<th>City Name</th>
<th></th>
</tr>
</thead>
<tbody formArrayName="cities">
<tr *ngFor="let city of cities; let i = index">
<td>{{i+1}}</td>
<td [formGroupName]="i">
<input type="text" formControlName="cityName" [ngClass]="{ 'border-less-textbox': city.cityID != editCityID, 'form-input': city.cityID == editCityID }" [disableControl]="city.cityID != editCityID" />
</td>
<td style="width:200px">
<button class="button button-blue-back" (click)="editClicked(city)" *ngIf="city.cityID != editCityID" type="button">Edit</button>
<button class="button button-blue-back" (click)="updateClicked(i)" *ngIf="city.cityID == editCityID" type="submit">Update</button>
<button class="button button-red-back ml" (click)="deleteClicked(city, i)" *ngIf="city.cityID != editCityID" type="button">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- right box begins -->
<div class="flex-1 w-50">
<div class="form-container">
<h3>Create City</h3>
<form [formGroup]="postCityForm" (ngSubmit)="postCitySubmitted()">
<!-- City Name-->
<div class="form-field flex">
<div class="w-25">
<label for="CityName" class="form-label pt">City Name</label>
</div>
<div class="flex-1">
<input type="text" class="form-input" formControlName="cityName" />
<span class="text-red" *ngIf="(postCity_CityNameControl.touched || isPostCityFormSubmitted) && (postCity_CityNameControl.errors?.['required'])">City Name can't be blank</span>
</div>
</div>
<div class="form-field flex">
<div class="w-25"></div>
<div class="flex-1">
<button class="button button-green-back">Create</button>
</div>
</div>
</form>
</div>
</div>
<!-- right box ends -->
</div>
3、cities.component.ts
import { Component } from '@angular/core';
import { FormArray, FormControl, FormGroup, Validators } from '@angular/forms';
import { City } from '../models/city';
import { CitiesService } from '../services/cities.service';
@Component({
selector: 'app-cities',
templateUrl: './cities.component.html',
styleUrls: ['./cities.component.css']
})
export class CitiesComponent {
cities: City[] = [];
postCityForm: FormGroup;
isPostCityFormSubmitted: boolean = false;
putCityForm: FormGroup;
editCityID: string | null = null;
constructor(private citiesService: CitiesService) {
this.postCityForm = new FormGroup({
cityName: new FormControl(null, [ Validators.required ])
});
this.putCityForm = new FormGroup({
cities: new FormArray([])
});
}
get putCityFormArray() : FormArray {
return this.putCityForm.get("cities") as FormArray;
}
loadCities() {
this.citiesService.getCities()
.subscribe({
next: (response: City[]) => {
this.cities = response;
this.cities.forEach(city => {
this.putCityFormArray.push(new FormGroup({
cityID: new FormControl(city.cityID, [Validators.required]),
cityName: new FormControl({ value: city.cityName, disabled: true }, [Validators.required]),
}));
});
},
error: (error: any) => {
console.log(error)
},
complete: () => { }
});
}
ngOnInit() {
this.loadCities();
}
get postCity_CityNameControl(): any {
return this.postCityForm.controls['cityName'];
}
public postCitySubmitted() {
this.isPostCityFormSubmitted = true;
console.log(this.postCityForm.value);
this.citiesService.postCity(this.postCityForm.value).subscribe({
next: (response: City) => {
console.log(response);
//this.loadCities();
this.putCityFormArray.push(new FormGroup({
cityID: new FormControl(response.cityID, [Validators.required]),
cityName: new FormControl({ value: response.cityName, disabled: true }, [Validators.required]),
}))
this.cities.push(new City(response.cityID, response.cityName));
this.postCityForm.reset();
this.isPostCityFormSubmitted = false;
},
error: (error: any) => {
console.log(error);
},
complete: () => { }
});
}
//Executes when the clicks on 'Edit' button the for the particular city
editClicked(city: City) : void {
this.editCityID = city.cityID;
}
//executes when the clicks on 'Update' button after editing
updateClicked(i: number): void {
this.citiesService.putCity(this.putCityFormArray.controls[i].value).subscribe({
next: (response: string) => {
console.log(response);
this.editCityID = null;
this.putCityFormArray.controls[i].reset(this.putCityFormArray.controls[i].value);
},
error: (error: any) => {
console.log(error);
},
complete: () => {},
});
}
deleteClicked(city: City, i: number) : void {
if (confirm(`Are you sure to delete this city: ${city.cityName}?`)) {
this.citiesService.deleteCity(city.cityID).subscribe({
next: (response: string) => {
console.log(response);
this.putCityFormArray.removeAt(i);
this.cities.splice(i, 1);
},
error: (error: any) => {
console.log(error);
},
complete: () => { },
})
}
}
}
结果
运行程序后显示Delete按钮并可以删除City
Gitee获取源码: