2017-09-11 10 views
0

私は角度2のタブコンポーネントで作業しています。angular2 - tabsコンテンツはローカルのjsonファイルからロードします

現在、私はPlunker例の下 Angular 2 Tabs

を以下の午前私はローカル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 
     ); 
    } 

} 

今コンポーネントファイルでそれを読み込む方法。

ここタブリンクでは、私が期待していは追加情報

  • 一般
  • ヘッダーとラベルで必要な説明

    • です。

      ご協力いただければ幸いです。

    答えて

    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を宣言するか、外部からそれをインポートします。あなたのplunker here

    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" 
          } 
         ] 
         } 
        ] 
        } 
    ]; 
    
    } 
    

    仕事フォーク

    +0

    ありがとうございました。それは私をたくさん助けた –

    1

    ローカルのJSONファイルの場合、なぜhttp呼び出しをしていますか?

    は単に

    let jsonFile = require('relative/path/to/json/file.json') 
    

    を行い、JSONファイルを読み取り、それはあなたのJSONファイルをロードする必要があります。

    関連する問題