用途
该技能用于生成一个 Angular 服务(service),该服务调用 up-api 的 CRUD 接口,针对给定实体提供数据访问能力。当用户提出 Day 2 相关需求时使用。
主要能力
生成的服务包含以下方法:
- getAll:获取全部数据
- getById:按 id 获取单条数据
- save:新增数据
- update:按 id 更新数据
- delete:按 id 删除数据
服务中同时定义与实体对应的 TypeScript 接口,字段与 Day 1 实体规格中的列一一对应。
使用方式
- 若当前对话中尚未确定实体,需先询问用户要操作哪个实体,且该实体必须与 up-api 的 CRUD 接口所暴露的实体一致。
- 生成文件路径为:up-app/src/app/services/<entity>.service.ts。
- 服务内容示例:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
export interface <Entity> {
id?: number;
// one field per column from the Day 1 entity spec
}
@Injectable({ providedIn: 'root' })
export class Service {
private base = 'http://localhost:8080/api/s';
constructor(private http: HttpClient) {}
getAll(): Observable<[]> { return this.http.get<[]>(this.base); }
getById(id: number): Observable<> { return this.http.get<>(${this.base}/detail/${id}); }
save(item: ): Observable<> { return this.http.post<>(this.base + '/save', item); }
update(id: number, item: ): Observable<> { return this.http.put<>(this.base + '/update/' + id, item); }
delete(id: number): Observable { return this.http.delete(this.base + '/' + id); }
}
- 若 app.config.ts 中尚未注册 provideHttpClient(),需要补充注册。
- 此步骤无需重新部署。
适用场景
适用于 Angular 前端项目需要对接 up-api 的 CRUD 接口、为某个实体快速生成数据访问服务的场景,属于 Day 2 培训流程中的第 2 步。
限制
- 实体必须与 up-api 的 CRUD 接口所暴露的实体一致。
- 基础地址固定为 http://localhost:8080/api/s。
- 接口字段需依据 Day 1 实体规格填写,资料中未提供具体字段内容。
- 其他收费、平台、效果等信息暂未提供。