2016-11-04 30 views
2

我正在使用智能管理模板以表格格式顯示數據。在angular2中動態綁定數據表不起作用

我試圖綁定數據與硬編碼的數據它的工作原理,但是當我從ngOnInit上的component.ts打到service.ts並設置爲this.data。雖然它設置但不顯示到ui/component.html。

請參閱下面的代碼。如果需要更多幫助,請讓我知道。

1. component.html裏面我寫了: -

<sa-datatable ng-data="data" [options]="{ 
       colReorder: true, 
       data: data, 
       columns: [ {data: 'apiKey'}, {data: 'name'}]}" 
       paginationLength="true" tableClass="table table-striped table-bordered table-hover" width="100%"> 
           <thead> 
            <tr> 
             <th data-hide="phone">APIKey</th> 
             <th data-class="expand"> 
              <i class="fa fa-fw fa-user text-muted hidden-md hidden-sm hidden-xs"></i> 
              Name 
             </th> 
            </tr> 
           </thead> 
</sa-datatable> 

2.內部component.ts

import { Component, OnInit } from '@angular/core'; 
import {JsonApiService} from "../shared/api/json-api.service"; 
import {Observable} from 'rxjs/Rx'; 
import {Router, CanActivate } from '@angular/router'; 

@Component({ 
    selector: 'administration-apps', 
    templateUrl: './administration.apps.component.html', 
    styleUrls: ['./administration.component.css'], 
    providers: [JsonApiService] 
}) 

export class AdministrationAppsComponent implements OnInit { 
    //data = [{ "_id": "5807f24c762c48a0b548318f", "accountID": "580170af762c48a0b548318e", "name": "EZ FORMSTest 4", "active": true, "apiKey": "b2878c30-bea0-11e4-983f-d9ec76fdf276" }, { "_id": "580170af762c48a0b008318e", "accountID": "580170af762c48a0b54831ff", "name": "EZ FORMSTest 5", "__v": 0, "active": true, "apiKey": "b2878c30-bea0-11e4-983f-d9ec76fdf276" }]; 

    private data: any; 
    private errorMessage: string; 
    constructor(private jsonApiService: JsonApiService, private router: Router) { 
    } 
    createNewApp() { 
     this.router.navigate(['/administration/apps/new']) 
    } 
    ngOnInit() { 
     this.data = this.jsonApiService.getApps() 
      .subscribe((apps: any) => { this.data = apps; console.log('looking for data now'); console.log(this.data);}, 
       error => this.errorMessage = error); 
    } 

} 

3內部JSON-api.service。 ts

getApps(): any { 
    return this.httpGet('/app'); 
} 
    httpGet(path) { 
    let headers = new Headers({ 'X-TOKEN': '2f348e80-a26c-11e6-aea2-  b1b9938df75f' }); 
    let options = new RequestOptions({ headers: headers }); 
    return this.http.get(this.baseURL + path, options) 
     .map((res: Response) => res.json()) 
     .map(forms => { 
      return forms; 
     }) 
     .catch(this.handleError); 
} 

回答

0

我試圖通過從API獲取響應來綁定數據表。

組件比獲取api響應數據更早加載。

對於那個我在運行時加載組件。

爲了動態這些都是幾個步驟加載部件: -

1.創建動態組件dynamic.component.ts

import {Component, Input, ViewContainerRef, ViewChild, ReflectiveInjector,   
    ComponentFactoryResolver} from '@angular/core'; 
    import {AdministrationAppsDatatableComponent} from   
    './administration.apps.datatable.component'; 

    @Component({ 
selector: 'dynamic-component', 
entryComponents: [AdministrationAppsDatatableComponent], // Reference to the  
components must be here in order to dynamically create them 
template: `<div #dynamicComponentContainer></div>`, 
}) 
export class DynamicComponent { 
currentComponent = null; 

@ViewChild('dynamicComponentContainer', { read: ViewContainerRef })  
dynamicComponentContainer: ViewContainerRef; 

// component: Class for the component you want to create 
// inputs: An object with key/value pairs mapped to input name/input value 
@Input() set componentData(data: { component: any, inputs: any }) { 
    if (!data) { 
     return; 
    } 

    // Inputs need to be in the following format to be resolved properly 
    let inputProviders = Object.keys(data.inputs).map((inputName) => { return { provide: inputName, useValue: data.inputs[inputName] }; }); 
    let resolvedInputs = ReflectiveInjector.resolve(inputProviders); 

    // We create an injector out of the data we want to pass down and this components injector 
    let injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.dynamicComponentContainer.parentInjector); 

    // We create a factory out of the component we want to create 
    let factory = this.resolver.resolveComponentFactory(data.component); 

    // We create the component using the factory and the injector 
    let component = factory.create(injector); 

    // We insert the component into the dom container 
    this.dynamicComponentContainer.insert(component.hostView); 

    // We can destroy the old component is we like by calling destroy 
    if (this.currentComponent) { 
     this.currentComponent.destroy(); 
    } 

    this.currentComponent = component; 
} 

constructor(private resolver: ComponentFactoryResolver) { 

} 
} 

2.創建administration.apps.datatable.component。 ts

import {Component, Injector} from '@angular/core'; 

@Component({ 
selector: "adminAppsHtml", 
template: `<sa-datatable [options]="tblOptions" 
             paginationLength="true" 
tableClass="table table-striped table-bordered table-hover" 
             width="100%"> 
      <thead> 
       <tr> 
        <th>APIKey</th> 
        <th>Name</th> 
       </tr> 
      </thead> 
     </sa-datatable> 

    ` 
    }) 

    export class AdministrationAppsDatatableComponent { 
tblOptions = {}; 
constructor(private injector: Injector) { 
    this.tblOptions = this.injector.get('options'); 
    console.log('looking for options in admin apps') 
    console.log(this.tblOptions); 
    } 
} 

3.在component.html中寫入如下內容: - 要顯示數據表記錄的位置。

<dynamic-component [componentData]="componentData"></dynamic-component> 

3包括administration.apps.datatable.component你在哪裏調用你的API像ngOnInit()方法,並在模塊還組件內。

import {AdministrationAppsDatatableComponent} from 
"./administration.apps.datatable.component"; 
ngOnInit() { 
    this.jsonApiService.getApps() 
     .subscribe((apps) => {   
     this.componentData = { 
      component: AdministrationAppsDatatableComponent, 
      inputs: { 
       options: { 
        colReorder: false, 
        data: apps, 
        columns: [{ data: 'apiKey' }, { data: 'name' }] 
       } 
      } 
     }; 
     }, 
     error => this.errorMessage = error); 

}

要獲得運行例子請按照我跟着

http://plnkr.co/edit/ZXsIWykqKZi5r75VMtw2?p=preview

鏈接