2016-11-28 12 views
2

私はAngular2アプリにいくつかの(初心者の)問題があります。まず、DIはあるコンポーネントでは動作しますが、別のコンポーネントでは動作しません。角度2依存注入(DI)は機能しません。

私は、主演の機能と食材のリストを含むカクテルの成分を持っています。以下のすべてのコードはストリップダウンされ、そしてそれはすべての罰金(何のコンソール・エラー)を実行していない - 私はちょうど所望の出力相続人

cocktail.component.ts届かない:

import { Component } from '@angular/core' 
import { CocktailService } from './cocktail.service' 
import { HttpModule } from '@angular/http'; 
import { Observable } from 'rxjs/Rx'; 

@Component({ 
    selector: 'cocktails', 
    templateUrl: 'app/cocktail.template.html', 
    providers: [CocktailService, HttpModule] 
}) 
export class CocktailsComponent { 
    title: string = "Sunday Brunch Specials"; 
    cocktails; 
    isStarred = false; 
    numLikes = 10; 
    ingredient_json = "Bob"; // for testing 

    constructor(private _cocktailService: CocktailService) { 
     this.cocktails = _cocktailService.getCocktails(); 
    } 

} 

、カクテルを。 template.html ....

<h2>{{title}}</h2> 
<input type="text" autoGrow /> 
    <ul> 
     <li *ngFor="let cocktail of cocktails | async"> 
     <h3>{{cocktail.name}}</h3> 
     <star [is-starred]="isStarred" [num-likes]="numLikes" (change)="onStarredChange($event)"></star> 
     <ingredients [ingredient-json]="ingredient_json"></ingredients> 
<li> 

スターコンポーネントが適切にisStarredとnumLikesを渡さなっている - すべての良いです。

import {Component, Input} from '@angular/core'; 
import {IngredientService} from './ingredient.service'; 
@Component({ 
selector: 'ingredients', 
template: ' 
     <h4>Ingredients</h4> 
     <ul> 
      <li *ngFor="let ingredient of ingredients">{{ingredient}}</li> 
     </ul>' 
)} 
export class IngredientsComponent { 
    @Input('ingredient-json') ingredient_json = "Hello"; 

    title: 'Ingredients'; 
    ingredients; 

    constructor() { 
     // Why isn't ingredient_json outputting anything but hello? Ie nothing is going into input 
     console.log("Ingredient JSON = " + this.ingredient_json); 
    } 
} 

私はコメントで述べてきた問題:成分コンポーネントで今

。これは、@ inputからインスタンス化されていません。私は何のエラーも出ません、コンソールはちょうどいつも 'Hello'を出力します - つまり、デフォルトです。 @Inputはその親(cocktail.component.ts)から何も取得していません。

私はこれらの3つのファイルに何か問題があるように感じるので、私はhaventすべてのアプリを含んでいます。私が言ったように、DIはコンポーネント上で動作するので、私はDIが動作することを知っていますが、私は下の私のコードで何が間違って見ることができません。 @input() paramsがコンポーネントに渡される前に

おかげでたくさん

+0

が 'はconsole.log( "成分JSON =" ...'すべてで実行されている)ingredient_json' 'なし(コンソールに出力 –

+0

うん、それだけでこの部分です –

答えて

4

コンストラクタが呼び出されます。

IngredientsComponentngOnChanges()メソッドを実装し、そこでconsole.log()を移動してください。ここ

詳細:??https://angular.io/docs/ts/latest/api/core/index/OnChanges-class.html

+0

は、面白いのですが、私の悪い、 –

+0

私の悪いことに、星のコンポーネントは同じです。ありがとうたくさんのので、本質的に@は、コンポーネントのJSON = hello ' –

+0

@Input()パラメータはバインディングを通されます。これはDIではありません。ngOnChanges()は、親のバインディング(メモリアドレス)が変更されるたびに呼び出されます。 –

関連する問題