2016-11-28 44 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); 
    } 
} 

这个问题我在评论中已经指出。这个ingredient_json变量并不是从@Input实例化的。我没有得到任何错误,控制台总是打印出'你好' - 即默认值。 @Input不会从其父节点(cocktail.component.ts)中获取任何内容。

我还没有包括所有的应用程序,因为我觉得在这3个文件中有什么不对劲。就像我说的那样,DI在组件上工作,所以我知道DI工作正常,但是我看不到下面的代码有什么问题。

感谢很多的@input() params传递给组件之前

+0

是'的console.log( “成分JSON =” ...'在所有正在执行的是这部分打印到控制台(不'ingredient_json') –

+0

是啊,它只是?打印出'Ingredient JSON = hello' –

回答

4

构造函数被调用。

在您的IngredientsComponent中实施方法ngOnChanges()并将您的console.log()移动到那里。

详情这里:https://angular.io/docs/ts/latest/api/core/index/OnChanges-class.html

+0

嗯,有趣,但为什么组件工作正常呢?我只是传递静态内容? –

+0

OK好吧,星级组件是一样的。输入(DI)项目在'施工'过程中不通过? –

+0

@Input()params通过绑定传递 - 它不是DI。每次父级绑定(内存地址)更改时,都会调用ngOnChanges()。 –