首页 > 解决方案 > 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);
    })
  }
}
<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>  

标签: angularhttp-posthttpclientcrudpatch

解决方案


推荐阅读