328 Angular DELETE

步骤

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

黄健华Yeah

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

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

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

打赏作者

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

抵扣说明:

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

余额充值