在Angular 2 API驱动的树视图中防止重复的HTTP请求
我有一个Angular 2应用程序调用
JSON API将数据加载到嵌套的HTML列表(< ol>).本质上是动态生成的树视图.由于API中的数据集最终会变得非常大,当用户打开分支时,树会逐渐填充(用户打开分支,使用已打开的节点的id调用API,API返回JSON对于节点的直接子节点的馈送,Angular将返回的JSON绑定到一些新的HTML< li>元素,并且树展开以显示新的分支).
您可以在此Plunkr中看到它的运行情况.它使用递归指令并且运行良好.目前,因为我无法打开公共请求的实际API,它只是调用静态JSON提要,因此每个节点的返回数据只是重复,但希望你能得到这个想法. 我现在要克服的问题是在分支关闭然后重新打开时防止无关的HTTP调用.阅读完HTTP client docs后,我希望这就像修改订阅数据服务的方法一样简单,将.distinctUntilChanged()方法链接到app / content-list.component.ts文件,如下所示: getContentNodes() { this._contentService.getContentNodes(this._startNodeId) .distinctUntilChanged() .subscribe( contentNodes => this.contentNodes = contentNodes,error => this.errorMessage = <any>error ); } 但是,当我打开浏览器网络检查器时,每次重新打开相同的树分支时,它仍然会调用API. 谁能建议如何解决这个问题? 非常感谢. 编辑: 我正试图在下面实施@Thierry Templier的答案;缓存API返回的数据.所以内容服务现在是: import {Injectable} from 'angular2/core'; import {Http,Response} from 'angular2/http'; import {Headers,RequestOptions} from 'angular2/http'; import {ContentNode} from './content-node'; import {Observable} from 'rxjs/Observable'; @Injectable() export class ContentService { constructor (private http: Http) {} private _contentNodesUrl = 'app/content.json'; _cachedData: ContentNode[]; getContentNodes (parentId:number) { if (this._cachedData) { return Observable.of(this._cachedData); } else { return this.http.get(this._contentNodesUrl + parentId) .map(res => <ContentNode[]> res.json()) .do( (data) => { this._cachedData = data; }) .catch(this.handleError); } } private handleError (error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } } 但是,这里发生的是当页面加载时,this._cachedData返回false并且API调用正在触发并使用返回的值(数据)填充this._cachedData,这是正确的.但是,当在网页UI中打开树节点时,以下行会重复运行数千次,直到最终浏览器崩溃: return Observable.of(this._cachedData); 当谈到Angular 2时,我仍然处于起步阶段,所以我真的很感激为什么这不能帮助我学习. 解决方法
我会使用以下方法缓存每个节点的数据:
getData() { if (this.cachedData) { return Observable.of(this.cachedData); } else { return this.http.get(...) .map(res => res.json()) .do((data) => { this.cachedData = data; }); } } distinctUntilChanged的“问题”是您需要使用相同的数据流.但是在你的情况下并非如此,因为你在不同的数据流上执行了几个请求…… 有关详细信息,请参阅此问题: > Angular 2,best practice to load data from a server one time and share results to components (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |