2.2.模板代码-删除
Service
src/app/plan/plan.service.ts
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Plan} from '../../domain/plan';
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
};
@Injectable({
providedIn: 'root'
})
export class PlanService {
constructor(private http: HttpClient) {
}
/**
* 删除计划
*
* @param id 计划的id
*/
deletePlan(id: string): Observable<any> {
const url = '/mo/v1/plan/' + id;
return this.http.delete(url);
}
}
父组件部分
模板
src/app/plan/plan.component.html
<a (click)="createDeleteModal(data)">删除</a>
控制器
src/app/plan/plan.component.ts
import {Component, OnInit, ViewContainerRef} from '@angular/core';
import {Plan} from '../../domain/plan';
import {PlanService} from './plan.service';
import {NzModalService} from 'ng-zorro-antd/modal';
import {PlanCreateComponent} from './plan-create/plan-create.component';
import {NzMessageService} from 'ng-zorro-antd';
@Component({
selector: 'app-plan',
templateUrl: './plan.component.html',
styleUrls: ['./plan.component.css']
})
export class PlanComponent implements OnInit {
constructor(private service: PlanService,
private modal: NzModalService,
private message: NzMessageService,
private viewContainerRef: ViewContainerRef) {
}
/**
* 创建删除对话框
*/
createDeleteModal(plan: Plan): void {
const modal = this.modal.confirm({
nzTitle: '删除计划',
nzContent: '确定删除计划" ' + plan.name + ' "吗?',
nzOnOk: () => {
// 调用api执行删除操作
this.deletePlan(plan.id);
}
});
// 当对话框开启时,打印日志
modal.afterOpen.subscribe(() => console.log('[afterOpen] emitted!'));
// 当对话框关闭时,返回结果
modal.afterClose.subscribe(result => console.log('[afterClose] The result is:', result));
}
/**
* 调用后台api删除计划
* @param id 计划id
*/
deletePlan(id: string): void {
// 提示删除中
const messageId = this.message.loading('正在删除中...', {nzDuration: 0}).messageId;
this.service.deletePlan(id).subscribe(
// 若调用api成功,打印api返回值,提示创建删除成功,并刷新列表
(data) => {
console.log('next: ' + data);
this.message.remove(messageId);
this.message.success('删除成功!');
this.refreshData();
},
// 若调用api失败,打印失败日志,提示删除失败
(error) => {
console.log('error: ' + error);
this.message.error('删除失败!');
this.message.remove(messageId);
}
);
}
/**
* 刷新数据
*/
refreshData(): void {
this.listPlans();
}
}
Last updated
Was this helpful?