步骤
1、更新cities.service.ts
添加postCity方法
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 })
}
}
2、更新cities.component.ts
import { Component } from '@angular/core';
import { 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;
constructor(private citiesService: CitiesService) {
this.postCityForm = new FormGroup({
cityName: new FormControl(null, [ Validators.required ])
});
}
loadCities() {
this.citiesService.getCities()
.subscribe({
next: (response: City[]) => {
this.cities = response;
},
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.cities.push(new City(response.cityID, response.cityName));
this.postCityForm.reset();
this.isPostCityFormSubmitted = false;
},
error: (error: any) => {
console.log(error);
},
complete: () => { }
});
}
}
3、更新cities.component.html
<h2>Cities</h2>
<div class="flex">
<div class="flex-1">
<div class="table-container">
<table class="table w-100">
<thead>
<tr>
<th>#</th>
<th>City Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let city of cities; let i = index">
<td>{{i+1}}</td>
<td>{{city.cityName}}</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>
4、更新app.module.ts
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CitiesComponent } from './cities/cities.component';
@NgModule({
declarations: [
AppComponent,
CitiesComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
结果
程序运行后显示如下,可以Create City
Gitee获取源码: