326 Angular POST

步骤

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获取源码:

https://gitee.com/huang_jianhua0101/asp.-net-core-8.git

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄健华Yeah

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值