微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在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();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?