我正在学习 Angular 2,尝试从(可能非常大)第三方 API 构建可扩展的树视图。该 API 的底层结构如下:
- Home (id: 1053)
- - Rugby League (id: 1054)
- - - Super League (id: 1103)
- - - - Castleford Tigers (id: 1111)
- - - - Catalans Dragons (id: 1110)
- - - - Huddersfield Giants (id: 1116)
- - - - Hull FC (id: 1108)
- - - Championship (id: 1104)
- - - - Batley Bulldogs (id: 1120)
- - - - Bradford Bulls (id: 1118)
- - - - Dewsbury Rams (id: 1124)
- - - - Featherstone Rovers (id: 1121)
- - Football (id: 1056)
- - - Premier League (id: 1057)
- - - - AFC Bournemouth (id: 1059)
- - - - etc
- - - - etc
API 的设置是这样的:我传递一个 id,它返回该节点(仅)子节点的简单 JSON 数组。因此,例如我调用:http://www.example.com/api/contentNodes/?parentId=1053
它返回:
[
{"Id":1054,"Name":"Rugby League","HasChildren":true},
{"Id":1056,"Name":"Football","HasChildren":true}
]
(HasChildren
表示该节点是否有子节点。)
请注意,因为数据集最终会很大,所以我想在打开树枝时逐渐从 API 中“拉入”更多数据,而不是将整个数据集转储到其中并在我的应用程序中渲染出来。
我已经设置了一个 Angular 2 应用程序,可以在此处看到:http://plnkr.co/edit/QQ1OKCbd4pDptpSVbWch?p=preview http://plnkr.co/edit/QQ1OKCbd4pDptpSVbWch?p=preview
关键组件是“app/content-list.component.ts”文件:
import {Component, OnInit} from 'angular2/core';
import {ContentNode} from './content-node';
import {ContentService} from './content.service';
@Component({
selector: 'content-list',
template: `
<ol class="tree">
<li *ngFor="#contentNode of contentNodes" class="tree__branch" [ngClass]="{'tree__branch--has-children': contentNode.HasChildren}">
<a *ngIf="contentNode.HasChildren" (click)="toggleBranch(contentNode.Id)" class="toggle">+</a> {{ contentNode.Name }}
</li>
</ol>
<div class="error" *ngIf="errorMessage">{{errorMessage}}</div>
`
})
export class ContentListComponent implements OnInit {
constructor (private _contentService: ContentService) {}
errorMessage: string;
private _startNodeId: number = 1053;
contentNodes: ContentNode[];
ngOnInit() {
this.getContentNodes();
}
getContentNodes() {
this._contentService.getContentNodes(this._startNodeId)
.subscribe(
contentNodes => this.contentNodes = contentNodes,
error => this.errorMessage = <any>error
);
}
toggleBranch(branchId:number){
console.log('branchId: ' + branchId);
}
}
您将在此处看到,我正在调用我的服务,该服务通过传递 1053 的 ParentId 来返回 JSON。
现在,我在能够逐步加载树视图的子节点方面遇到了困难。+
单击按钮,进入嵌套 HTML 列表(<ol>
).
以一种非常巧妙的方式实现这一目标的最佳方法是什么?
我的下一步将是确保应用程序不会进行过多的 API 调用,但我最关心的是让正在运行的树视图连接起来并正常工作。
我见过这个递归树视图的例子 http://www.syntaxsuccess.com/viewarticle/recursive-treeview-in-angular-2.0但似乎(a)有点问题(因为有空<ol></ol>
当子节点为空时在 HTML 中呈现的元素等); (b)它似乎是以一种非常“硬编码”的方式设置的,而且我没有足够的经验来自信地重构它。
非常感谢。
请注意,不幸的是,出于安全原因,我无法向公共请求开放 API,我意识到这使得在 Plunkr 上进行测试变得有点困难。目前,我的示例仅使用静态、单级 JSON 数据集。