我在Angular 2选项卡组件上工作。
目前我正在关注下面的plunker示例Angular 2选项卡
我需要通过读取本地JSON文件来动态。
我的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
);
}
}
现在如何在组件文件中读取它。
在 TAB 链接中,我希望是
- 附加信息
- 一般
标题和标签所需的描述。
任何帮助将不胜感激。
您在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"
}
]
}
]
}
];
}
在这里工作的叉子
如果是本地JSON文件,为什么要进行HTTP调用?
要阅读一个JSON文件,只需做
let jsonFile = require('relative/path/to/json/file.json')
,它应该加载您的JSON文件。