2016-09-27 68 views
3

我在使用對象爲管* ngFor,當我在我的組件聲明管 - 我得到這個錯誤(VS代碼) - >管誤差ngFor在對象

[ts] Argument of type '{ selector: string; templateUrl: string; pipes: typeof ObjNgFor[]; providers: typeof TableCompone...' is not assignable to parameter of type 'ComponentMetadataType'. 
    Object literal may only specify known properties, and 'pipes' does not exist in type 'ComponentMetadataType' 

這是我的組件:

import { Component, OnInit, Pipe, PipeTransform } from '@angular/core'; 

     @Pipe({ name: 'ObjNgFor', pure: false }) 
     export class ObjNgFor implements PipeTransform { 
      transform(value: any, args: any[] = null): any { 
       return Object.keys(value).map(key => Object.assign({ key }, value[key])); 
      } 
     } 

     @Component({ 
      selector: 'tablecomponent', 
      templateUrl: 'app/table.template.html', 
      pipes: [ObjNgFor], 
      providers: [TableComponentService] 
     }) 
     export class TableComponent implements OnInit { 

      lists: any; 

      constructor(public _service: TableComponentService) { 

      } 

     ngOnInit() { 
     this._service.getServices() 
      .subscribe(lists => this.lists = lists) 
      } 

     } 

,這是我的模板與*ngFor direcrive部分:

<tr *ngFor="let list of lists | ObjNgFor"> 
       <td>{{ list.name}}</td> 
       <td></td> 
       <td></td> 
       <td></td> 
       <td></td> 
</tr> 
+0

你可以有一個管道名稱與類名稱不完全相同嗎? –

+0

@Harry Ninh你的意思是重命名管道或類?它不仍然工作 –

回答

6

隨着最新版本的角度你不能使用pipesdirectives參數@Component元數據,以便從@Component刪除pipes並將其添加到您的模塊聲明如下:

import { Component, NgModule, OnInit, Pipe, PipeTransform } from '@angular/core'; 
import { HttpModule } from '@angular/http'; 

@Pipe({ name: 'objngfor', pure: false }) 
export class ObjNgFor implements PipeTransform { 
    transform(value: any, args: any[] = null): any { 
    return Object.keys(value).map(key => Object.assign({ key }, value[key])); 
    } 
} 

@Component({ 
    selector: 'tablecomponent', 
    templateUrl: 'app/table.template.html' 
}) 
export class TableComponent implements OnInit { 
    lists: any; 
    constructor(public _service: TableComponentService) {} 
    ngOnInit() { 
    this._service.getServices().subscribe(lists => this.lists = lists) 
    } 
} 

@NgModule({ 
    imports  : [HttpModule], 
    declarations : [TableComponent,ObjNgFor], 
    providers : [TableComponentService] 
}) 
export class AppModule { 
} 
+0

感謝您快速回答!在app.module.ts我添加我的管道這個導入命令:'從'./table.component';'導入{ObjNgFor},並聲明'聲明:[AppComponent,TableComponent,ObjNgFor]',現在我有這個錯誤 - >'原來的例外:不能將undefined或null轉換爲對象' –

+0

你會得到這個錯誤嗎?在你的管道? – ranakrunal9

+0

不,從調試器在crome –

0

讓你管的名字從管類名稱不同。

例子:

@Pipe({ name: 'objngfor', pure: false }) 

相反

@Pipe({ name: 'ObjNgFor', pure: false }) 

,改變像

<tr *ngFor="let list of lists | objngfor"> ... </tr> 

希望這有助於你的模板代碼!