在Angular中向视图与数据库新增元素后如何在未知ID时直接删除
解决方案
核心实现方案(改造成本最低)
只需调整两个环节即可解决问题,不需要修改现有业务逻辑,也不用前端生成ID、不用全量拉取列表:
- 首先让后端
POST /folders接口在创建成功后,直接返回完整的新文件夹对象,包含数据库自动生成的folderId,结构和GET /folders返回的单条Folder结构完全一致即可。 - 修改
FoldersService的createNewFolder方法,拿到后端返回的带ID的文件夹对象后直接更新本地缓存:
createNewFolder(newFolder: Folder) { this.http // 声明响应类型为Folder .post<Folder>(this.url+this.endpoint, { "title": newFolder.title }) .subscribe( (createdFolder) => { console.log("Successfully added."); // 直接把后端返回的带真实ID的文件夹加入本地数组 this.folders.push(createdFolder); // 触发视图更新,无需调用全量getFolders this.emitFolderSubject(); }, (error) => { console.log("Error : ", error); } ) }
兼容方案(无法修改后端时使用)
如果后端接口不能调整返回值,可要求后端在POST响应的Location头中返回新资源的地址(标准RESTful规范默认就支持该逻辑),前端从响应头解析出ID后补全到本地对象即可:
createNewFolder(newFolder: Folder) { this.http .post(this.url+this.endpoint, { "title": newFolder.title // 配置拿到完整响应对象(包含头信息) }, { observe: 'response' }) .subscribe( (response) => { console.log("Successfully added."); // 从Location头解析ID,示例:Location值为/folders/12,拆分后拿到12 const location = response.headers.get('Location'); const folderId = Number(location.split('/').pop()); // 补全文件夹ID newFolder.folderId = folderId; this.folders.push(newFolder); this.emitFolderSubject(); }, (error) => { console.log("Error : ", error); } ) }
内容的提问来源于stack exchange,提问作者Paul Serre
相关产品推荐
相关产品推荐

