2016-07-30 13 views
2

私がやりたいことはかなり単純です.のObservableを返す関数getListDataがあり、それをPerson [ ]。TypeError:プロパティ 'length'を読み取ることができません(typescript/Observable/angular2)

enter image description here

と、この:私がログインしたときに

EXCEPTION: TypeError: Cannot read property 'length' of undefined in [listToDisplay in [email protected]:60]

これは私が得るものlistToDisplayです:

@Injectable() 
    export class AppCmp implements OnInit { 

    listToDisplay: Person[]; 

    showingPerson = false; 

    constructor(private _myService: MyService) { 
    }; 

    public showMatcherData(): void { 
     this.showingPerson = true; 
     this. _myService.getListData().subscribe(res => { 
     this.listToDisplay = res; 
     }) 
    } 

が、私はエラーを取得:

は、だから私はそれをやりましたどのように私はそれを提示している:

<div *ngIf="showingPerson"> 
    <div dnd-sortable-container [dropZones]="['zone-one']" [sortableData]="listToDisplay"> 
     <div class="list-bg" *ngFor="#per of listToDisplay; #i = index" dnd-sortable [sortableIndex]="i"> 
     ID: {{per.id}} <p></p> age: {{per.age}} 
     </div> 
    </div> 
    </div> 

場合イム使用してPERSON2:

はそれが動作する代わりにlistToDisplayの
let person2 =() => { 
    return [ 
    { 
     "id": "2323", 
     "age": 22 
    }, 
    { 
    "id": "2323", 
     "age": 22 
    } 
    , 
    { 
    "id": "2323", 
     "age": 22 
    } 
    ] 

}; 

、どのように来ますか?

どういう意味ですか、どうすれば修正できますか?

+0

1) '注射用()'行を削除します。 2) 'ngOnInit'が実装されていることを確認してください。3)まだ動作しない場合は、' getListData() 'コードを表示してください。 4) 'html'も問題になる可能性があります。 – micronyks

+0

注射が必要で、ngOnInItが実装されています。コードの簡素化を送信しました。 – Joe

+0

'this.listToDisplay'でデータを取得しますか?コンソールでチェックインしてください。 – micronyks

答えて

1

問題は、このsortableDataに関連することができます

<div dnd-sortable-container [dropZones]="['zone-one']" [sortableData]="listToDisplay"> 

ない*ngFor。あなたが今しているようにあなたがいない前に、データをロード後*ngIfであるフラグを変更する、つまり)

<div *ngIf="showingPerson"> 

あなただけの全体のものが表示されます。

ので、この:

public showMatcherData(): void { 
    this.showingPerson = true; // <------------------------------ line will move 
    this. _myService.getListData().subscribe(res => { 
    this.listToDisplay = res; 
    }) 
} 

はなるはずです。

public showMatcherData(): void { 
    this. _myService.getListData().subscribe(res => { 
    this.listToDisplay = res; 
    this.showingPerson = true; // <------------------------------ line moved 
    }) 
} 
+0

それは素晴らしいです。私はこれがうまくいくと思います。 – micronyks

関連する問題