2016-05-01 18 views
2

に定義されていない私は、このコンポーネントがあります:コンポーネントのテンプレートで角度2:のOnInit時のプロパティセットをテンプレート

export class CategoryDetailComponent implements OnInit{ 
    category: Category; 
    categoryProducts: Product[]; 
    errorMessage: string; 
    constructor(private _categoryService: CategoryService, private _productService: ProductService, private _routeParams: RouteParams) {} 

    ngOnInit() { 
    this.getCategoryAndProducts(); 
    } 
    getCategoryAndProducts() { 
    let categoryName = this._routeParams.get('name'); 
    let categoryId = this.routeParams.get('id'); 
    var params = new URLSearchParams(); 
    params.set('category', categoryName); 

    Observable.forkJoin(
     this._categoryService.getCategory(categoryId), 
     this._productService.searchProducts(params) 
    ).subscribe(
     data => { 
     //this displays the expected category's name. 
     console.log("category's name: "+ data[0].attributes.name) 
     this.category = data[0]; 
     this.categoryProducts = data[1]; 
     }, error => this.errorMessage = <any>error 
    ) 
    } 
} 

を私はこれを持っている:

<h1>{{category.attributes.name}}</h1> 

私はこのコンポーネントに移動し、

なぜテンプレートのcategoryプロパティが定義されていないのですか。どうすればこの問題を解決できますか?

+2

使用エルビス演算子カテゴリ.attributesは、あなたが – yurzui

+0

説明してくださいすることができます.nameのそれがなぜ私がそれを受け入れることができるように働いたのか答えてください。 –

+0

問題は、カテゴリオブジェクトを非同期で初期化することです。空のオブジェクトカテゴリを初期化することができます:Category = {attributes:[]} – yurzui

答えて

5

テンプレートの結合は、ngOnInit()の前に評価される。 categoryが値を持っていない限り、あなたは

<h1>{{category?.attributes.name}}</h1> 

を使用することができ、エラーをスローするように角度防ぐためにエルビス演算子は.attributes...を評価角度防ぐことができます。

2

変数を初期化することでも解決できます。

のInitこの宣言ながら:

export class CategoryDetailComponent implements OnInit{ 
    category: Category = new Category(); 
    ... 
    ... 
} 

またはinitをコンポーネントのコンストラクタで:??それは働いた@yurzui

constructor(....) { 
    this.category = new Category(); 
} 
関連する問題