angular - Angular HTTPClient 动态获取 Id
问题描述
有人可以告诉我如何动态更新和删除特定项目吗?我在我的代码中硬编码了 ID 号,并希望使其动态化。如果我不对其进行硬编码,控制台日志只会显示一个空对象,并且更新或删除功能都不能正常工作。请让我知道我应该如何改进代码。谢谢!
- 后端服务文件
private url = 'https://jsonplaceholder.typicode.com';
constructor(private httpClient: HttpClient) { }
public get()
{
// let id: number;
let endPoints = "/posts/";
return this.httpClient.get(this.url + endPoints);
}
public getById()
{
let id: number = 1;
let endPoints = "/posts/" + id;
return this.httpClient.get(this.url + endPoints);
}
public post(postData: Object) {
let endPoints = "/posts";
return this.httpClient.post(this.url + endPoints, postData);
}
public patch(postData: Object) {
let id: number = 1;
let endPoints = "/posts/" + id;
return this.httpClient.patch(this.url + endPoints, postData);
}
public delete(postData: Object) {
let id: number = 1;
let endPoints = "/posts/" + id;
return this.httpClient.delete(this.url + endPoints, postData);
}
}
- 帖子组件
id=[];
data= [];
constructor(private backendService: BackendService) { }
ngOnInit() {
this.backendService.get().subscribe((res:any[]) =>{
console.log(res);
this.data = res;
})
}
getById() {
this.backendService.getById().subscribe((res:any[]) => {
console.log(res);
this.data = res;
})
}
createPost(input: HTMLInputElement) {
let post = {title: input.value};
input.value="";
this.backendService.post(post).subscribe(response => {
// post['id']=response.id;
this.id=post['id'];
this.data.splice(0,0,post);
console.log(response);
});
}
updatePost(post) {
this.backendService.patch(post).subscribe((response:any) => {
console.log(response);
})
}
deletePost(post) {
this.backendService.delete(post).subscribe(response => {
let index = this.data.indexOf(post);
this.data.splice(index,1);
console.log(response);
})
}
}
- 帖子 html
<ul class="list-group">
<li *ngFor="let item of data" class="list-group-item">
{{item.id}}
{{item.title}}
<button
(click)="updatePost(post)"
class="btn btn-default btn-sm">Update</button>
<button
(click)="deletePost(post)"
class="btn btn-default btn-sm">Delete</button>
</li>
<button
(click)="getById()">
Get By Id</button>
</ul>
解决方案
推荐阅读
- c - 如何在结构中分配内存使其连续
- html - 同时在 HTML 和 CSS 规则中的 style 标签
- java - 休眠会话不更新实体
- node.js - heroku 构建失败。"mongoUrl"://"mongodb........" 语法错误等等
- asp.net-core - 即使在搭建所有身份页面后也找不到身份的 Layout.cshtml 文件
- javascript - Javascript 继承:原型链如何在原生原型之间工作
- python - 使用 Python 未收到 Gmail API 的完整正文消息
- node.js - 如何修复在 npm 中运行任何定义的脚本失败并出现错误 3221225781
- go - 如何在 Go 中逐行处理文件?
- batch-file - 使用批处理脚本将文件放在以它们命名的新文件夹中,如何让它忽略下划线和句点之间的所有内容?