我的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
传递给组件之前
是'的console.log( “成分JSON =” ...'在所有正在执行的是这部分打印到控制台(不'ingredient_json') –
是啊,它只是?打印出'Ingredient JSON = hello' –