Angular2 +"无法读取未定义的属性X"

时间:2017-05-25 17:44:06

标签: angular typescript

使用对象定义组件中显示的数据。现在通过Http服务读入来自json文件的数据,并收到此错误: enter image description here

看起来它在我的主要组件中失败了:

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"的问题。

我怎样才能绕过它?

2 个答案:

答案 0 :(得分: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;
  });
}

答案 1 :(得分: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;
    }
  }
}