嗨,我对angular完全陌生,在尝试在父组件中使用服务时遇到了问题。
下面是代码,其中“ recipe.component.ts ”是我的父类,“ recipe-list.component.ts ”是我的子类,最后“ recipe.service.ts ”是服务类别。
我要做的就是使用提供者,使用服务类中的服务通过父组件 >”在父组件中。
我相信在父组件中使用“提供程序”将有助于其他子组件使用该类的相同实例。
由于某些原因,我不知道我是否遇到以下错误。
我尝试过的事情:
非常感谢您的帮助。预先感谢!
ERROR Error: StaticInjectorError(AppModule)[RecipeListComponent -> RecipeService]:
StaticInjectorError(Platform: core)[RecipeListComponent -> RecipeService]:
NullInjectorError: No provider for RecipeService!
at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get (core.js:3228)
import { Component, OnInit } from '@angular/core';
import { RecipeModel } from './recipe.model';
import { RecipeService } from './recipe.service';
@Component({
selector: 'app-recipe',
templateUrl: './recipe.component.html',
styleUrls: ['./recipe.component.css'],
providers: [RecipeService]
})
export class RecipeComponent implements OnInit {
recipeDetails: RecipeModel;
constructor(private recipeService: RecipeService) { }
ngOnInit() {
}
onReceiveSecondEvent(recipeEvent: RecipeModel){
this.recipeDetails= recipeEvent
}
}
import { Component, OnInit,Output,EventEmitter } from '@angular/core';
import { RecipeModel } from '../recipe.model';
import { RecipeService } from '../recipe.service';
@Component({
selector: 'app-recipe-list',
templateUrl: './recipe-list.component.html',
styleUrls: ['./recipe-list.component.css'],
})
export class RecipeListComponent implements OnInit {
@Output() SecondRecipeEvent= new EventEmitter<RecipeModel>();
recipes: RecipeModel[];
constructor(private recipeService: RecipeService) {
}
ngOnInit() {
this.recipes= this.recipeService.getRecipe();
}
onReceiveEvent(recipe: RecipeModel){
this.SecondRecipeEvent.emit(recipe)
}
}
import { RecipeModel } from './recipe.model';
export class RecipeService{
recipes: RecipeModel[]=[
new RecipeModel('Cake Recipe','A recipe for Chocolate Cake',
'recipeCake.png')
];
getRecipe(){
return this.recipes.slice();
}
}