在上個章節,有關路由的設計,可以參考app-routing.module.ts的下述的程式碼:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { EmployeeListComponent } from './employee-list/employee-list.component';
import { EmployeeDetailComponent } from './employee-detail/employee-detail.component';
import { EmployeeSalesListComponent } from './employee-sales-list/employee-sales-list.component';
import { EmployeeAddComponent } from './employee-add/employee-add.component';
const routes: Routes = [
{ path: '', redirectTo: '/employeesaleslist', pathMatch: 'full' },
{ path: 'employeelist', component: EmployeeListComponent },
{ path: 'employeesaleslist', component: EmployeeSalesListComponent },
{ path: 'employeeinfo/:id', component: EmployeeDetailComponent},
{ path: 'employeeadd', component: EmployeeAddComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
接下來,說明如何刪除資料。首先,在employeeservice.service中,增加deleteEmployeeinfo的函式來刪除員工資料,主要是用輸入的參數,將Employeeinfo物件輸入到函式中,取得id值後,再透過http.delete,來刪除整個Employeeinfo,程式碼如下:
// 刪除員工資料
deleteEmployeeinfo(employeeinfo: Employeeinfo | number): Observable<Employeeinfo> {
const id = typeof employeeinfo === 'number' ? employeeinfo : employeeinfo.id;
const url = `${this.employeeUrl}/${id}`;
return this.http.delete<Employeeinfo>(url, httpOptions)
.pipe(
catchError(this.handleError<Employeeinfo>(`getEmployeeinfo id=${id}`))
);
}
在處理好Service後,接下來,在原來的員工資料明細,增加一個刪除的按鈕及呼叫Service的函式。在employee-detail.component.ts中,增加呼叫Service的函式,將完整的employee物件,輸入函式中。程式碼如下:
// 刪除員工資料
deleteinfo(): void {
this.employeeService.deleteEmployeeinfo(this.employee)
.subscribe();
}
在employee-detail.component.html中,增加一個刪除的按鈕,在(click)事件中,繫結到deleteinfo()函式。程式碼如下:
<button (click)="deleteinfo()">刪除</button>
完成了刪除,就完成了資料庫的基本操作。