我正在研究angular 2 Tabs组件。
目前我正在关注Plunker示例 Angular 2 Tabs
我需要通过阅读Local JSON文件使Tabs动态化。
我的JSON
[
{
"id": "1",
"name": "General",
"content": [
{
"header": "Basic Information",
"contents": [
{
"label": "Report goes here"
}
]
}
]
},
{
"id": "2",
"name": "Additional info",
"content": [
{
"header": " Information",
"contents": [
{
"label": "Report goes here"
}
]
}
]
}
]
Service.ts
export class DashboardService{
private _url: string = "assets/sample.json";
constructor( private _http: Http){}
getRecords(){
return this._http.get(this._url)
.map((response:Response) => response.json())
.catch(this._errorHandler);
}
_errorHandler(error: Response){
console.error(error);
return Observable.throw(error || "Server Error");
}
}
Component.ts
export class DynamicTabsComponent implements OnInit{
records = [];
errorMsg: string;
constructor(private _dashboardService: DashboardService) { }
ngOnInit() {
this._dashboardService.getRecords()
.subscribe(
resGetRecords => this.records = resGetRecords,
resRecordsError => this.errorMsg = resRecordsError
);
}
}
现在如何在组件文件中阅读它。
此处在标签链接中,我期待的是
标题和标签需要说明。
任何帮助都将不胜感激。
答案 0 :(得分:1)
如果是本地JSON文件,为什么要进行http调用?
要阅读JSON文件,只需执行
let jsonFile = require('relative/path/to/json/file.json')
它应该加载你的JSON文件。
答案 1 :(得分:1)
你在你的json上做* ngFor来显示标签:
<tabs>
<tab *ngFor="let tab of tabs" tabTitle="{{tab.name}}">
<div>{{tab.content[0].header}}</div>
<div>{{tab.content[0].contents[0].label}}</div>
</tab>
</tabs>
您将json声明为组件或从外部导入:
class App {
tabs = [
{
"id": "1",
"name": "General",
"content": [
{
"header": "Basic Information",
"contents": [
{
"label": "Report goes here"
}
]
}
]
},
{
"id": "2",
"name": "Additional info",
"content": [
{
"header": " Information",
"contents": [
{
"label": "Report goes here"
}
]
}
]
}
];
}
你的plunker的工作叉here