如何在Angular中使用json服务器获取JSON文件的最后记录?

问题描述

我有一个JSON文件,我正在执行发布请求,然后获取请求。我想在每个发布请求之后获取每个get请求中的最后一条记录。例如:

[
  {
    "id": 1,"title": "json-server","author": "typicode"
  },{
    "report": "1","park": "1","use": "7","group": "60","privateplin": "30","privateplus": "30","first": "30","second": "30","id": 2
  },"use": "9","id": 3
  },"park": "2","id": 4
  },]

我想获取ID为4的记录,但是在下一个帖子请求之后,我希望获取ID为5的记录,等等。

public getJSON(): Observable<any> {

    
     return this.httpclient.get("http://localhost:3000/posts/4").pipe(
        catchError(this.errorHandler));

                     

 }

解决方法

尝试一下

counter:number;

constructor(){
     this.counter=0;
}

public getJSON(): Observable<any> {

    this.counter=this.counter+1;
     return this.httpclient.get("http://localhost:3000/posts/"+this.counter).pipe(
        catchError(this.errorHandler));

 }

或者您可以将计数器保存在组件中,并作为参数将计数器发送给该方法。

 public getJSON(counter): Observable<any>

创建帖子请求时,需要保存ID。

,

首先,您需要具有一个变量,以将记录的当前id存储在JSON文件中。 然后,在每个POST请求之后,您可以为该变量递增或分配新的ID。

要基于您的currentId获得结果,您将需要遍历从那里的服务器返回的JSON数据:

例如:

currentId = 1;

this.getJSON.subscribe((response)=>{
  if(response) {
    response.forEach((item)=>{
      if(item.id===currentId) {
       //do your operations with the selected Item
      }
  });
});

public function yourPostRequest(){

// increment or assign currentId on success
currentId++;

}

如果您有来自getJson的静态数据,那么我建议您将其存储在变量上并对其进行迭代,而不是每次都获取它:

currentId = 1;
jsonData = [];

constructor(){

this.getJSON();

}

this.getJSON.subscribe((response)=>{
  if(response) {
    this.jsonData = response;
    this.updateCurrentId();
  });
});

public function updateCurrentId(){
   this.jsonData.forEach((item)=>{
      if(item.id===currentId) {
       //do your operations with the selected Item
      }
}

public function yourPostRequest(){

// increment or assign currentId on success
currentId++;
this.updateCurrentId();
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...