【问题标题】:Angular observable caching dataAngular 可观察缓存数据
【发布时间】:2019-05-21 00:20:06
【问题描述】:

我有一个基于 Angular 6 的 Angular 项目,我的 API 是 .net core 2.1.

我已经实现了分页。 使用 postman 在我的 .net core API 中调用我的分页方法效果很好。 从角度端,我使用一个可观察的。在ngOnInit 事件上,我调用fetchRecords() 函数并显示前10 条记录。当我单击下一步时,我再次调用fetchRecords() 方法并传入正确的分页参数,但页面仍然保持前10条记录,我还在console.log()中注意到来自API的记录仍然相同前 10 条记录。我有一个刷新按钮,它再次调用fetchRecords() 方法,当我立即单击刷新按钮时,没有任何变化。但如果我等待大约 7 秒以上,则会显示接下来的 10 条记录。 在我的 observable 中是否有某种缓存可以保持请求响应几秒钟?如果是这样,我该如何纠正这个问题?

/* My Fetch Requests method in my component.ts */

fetchRecords(){

let requestData:any = {
   skip: (this.page * this.rowsPerPage) - this.rowsPerPage,
   take: this.rowsPerPage
}


this.api.post('apiUrl/fetchRecords', requestData).subscribe(res=>{ // this is where i subscribe
 console.log('results', res); // Does not change unless delayed for 10 seconds
}
error=>{

})

}



goToNextPage(){
  this.page = this.page + 1;
    this.fetchRecords(); 
}

goToPreviousPage(){
  this.page = this.page - 1;
    this.fetchRecords();
}



/* Post Method */

post(url, obj) : Observable<any>{
    return this.http.post(`${this.baseUrl}/${url}`, obj, this.options)
    .map((response: Response) => {
        return response.json();
    });
}

【问题讨论】:

  • 你必须告诉更多关于this.api.post('apiUrl/fetchRecords', requestData).的细节
  • 你可能在你的角度中的某个地方遇到了竞争条件。在完全加载之前尝试使用新值
  • @ABOS 好的,我已经更新了问题。
  • @NikolaiKiefer 但是当我从邮递员那里调用 .net core api 时,结果还可以
  • 为什么仍然可以使用 response.json?

标签: angular typescript rxjs observable


【解决方案1】:

我找到了解决方案。 显然我只是意识到来自http请求的角度缓存响应。我尝试添加无缓存缓存控制标头和所有这些,但它没有工作。最终起作用的是将唯一的日期字符串作为参数附加到我的帖子 url(成功地使每个请求 url 唯一),并且我的请求现在即使连续快速加载也可以正常加载。这是代码的sn-p

post(url, obj) : Observable<any>{
    return this.http.post(`${this.baseUrl}/${url}`+ "?"+new Date().toString(), obj, this.options)
    .map((response: Response) => {
        return response.json();
    });
}

感谢大家的贡献。

【讨论】:

    猜你喜欢
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    相关资源
    最近更新 更多