2017-05-25 14 views
0

オブジェクトを使用して、コンポーネントに表示されるデータを定義します。 HTTPサービス経由で読み込まれる今のJSONファイルからのデータで配管し、このエラーを取得: enter image description hereAngular2 + "プロパティXを未定義に読み込めません"

、それはここにある私のメインコンポーネント内で失敗しているように見えます:

import { Component, OnInit } from '@angular/core'; 
import { FormsModule } from '@angular/forms'; 
import { Contribution } from '../contribution'; 
import { ContribService } from '../contrib.service'; 
import { Card } from '../card'; 
import { Group } from '../group'; 

@Component({ 
    providers: [ContribService], 
    selector: 'main', 
    templateUrl: './main.component.html', 
    styleUrls: ['./main.component.css'] 
}) 
export class MainComponent implements OnInit{ 
    contrib:Contribution = new Contribution(); 
    constructor(private contribService: ContribService){ 

    } 
    ngOnInit(){ 
    this.contribService.getContribution().subscribe(data=>this.contrib = data); 
    } 
    maskCard: boolean = true; 
    unmaskedCard: string = this.contrib.thisCard.number; 
    maskedCard: string = 'XXXXXXXXXXXX' + this.unmaskedCard.substring(11,15); 
    displayedCard: string = this.maskedCard; 
    maskToggle = function(): void{ 
    if(this.maskCard == true){ 
     this.displayedCard = this.maskedCard; 
    }else{ 
     this.displayedCard = this.unmaskedCard; 
    } 
    } 
} 

私が理解しているところでは、エラーはオブジェクト "thisCard"の問題以上の可能性があります。

どうすれば回避できますか?

+0

の可能性のある重複(https://stackoverflow.com/questions/43055706:データが解決された初期化を移動してみてください[私はangular2において観察/ HTTP /非同期呼び出しからの応答を返すにはどうしますか?] /どのようにdo-i-return-the-observable-http-async-call-in-angular2からの応答2) – Alex

答えて

1

this.contribを設定しているサブスクリプションに初期化コードの残りの部分を移動します。それ以外の場合は、サブスクリプションが完了する前に設定されています。

unmaskedCard: string; 
maskedCard: string; 
displayedCard: string; 

ngOnInit(){ 
    this.contribService.getContribution().subscribe(data=> { 
    this.contrib = data; 
    this.unmaskedCard = this.contrib.thisCard.number; 
    this.maskedCard = 'XXXXXXXXXXXX' + this.unmaskedCard.substring(11,15); 
    this.displayedCard = this.maskedCard; 
    }); 
} 
0

必要なデータが解決される前にプロパティを設定しています。

export class MainComponent implements OnInit{ 
    contrib:Contribution = new Contribution(); 
    maskCard: boolean; 
    unmaskedCard: string; 
    maskedCard: string; 
    displayedCard: string; 
    constructor(private contribService: ContribService){ 

    } 
    ngOnInit(){ 
    this.contribService.getContribution().subscribe(data=> { 
     this.contrib = data; 
     this.maskCard = true; 
     this.unmaskedCard = this.contrib.thisCard.number; 
     this.maskedCard = 'XXXXXXXXXXXX' + this.unmaskedCard.substring(11,15); 
     this.displayedCard = this.maskedCard; 
    }); 
    } 

    maskToggle = function(): void{ 
    if(this.maskCard == true){ 
     this.displayedCard = this.maskedCard; 
    }else{ 
     this.displayedCard = this.unmaskedCard; 
    } 
    } 
} 
関連する問題