错误错误:StaticInjectorError(AppModule):NullInjectorError:没有提供程序

时间:2019-02-03 20:05:18

标签: angular6 angular2-services angular7

嗨,我对angular完全陌生,在尝试在父组件中使用服务时遇到了问题。

下面是代码,其中“ recipe.component.ts ”是我的父类,“ recipe-list.component.ts ”是我的子类,最后“ recipe.service.ts ”是服务类别。

我要做的就是使用提供者,使用服务类中的服务通过父组件 >”在父组件中。

我相信在父组件中使用“提供程序”将有助于其他子组件使用该类的相同实例。

由于某些原因,我不知道我是否遇到以下错误。

我尝试过的事情:

  1. 试图将 Providers 放置在子组件 recipe-list.component.ts 中,并且有效。
  2. 试图将提供程序放在 app.module.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)

recipe.component.ts

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
  }
}

recipe-list.component.ts ##

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)

      }
    }

recipe.service.ts

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();
      }
}

0 个答案:

没有答案