angular学习007提示服务注入错误AppComponent.html:2 ERROR Error: StaticInjectorError(AppModule)[HeroesComponent

1、错误

AppComponent.html:2 ERROR Error: StaticInjectorError(AppModule)[HeroesComponent -> HeroService]: 
  StaticInjectorError(Platform: core)[HeroesComponent -> HeroService]: 
    NullInjectorError: No provider for HeroService!
    at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get (core.js:951)
    at resolveToken (core.js:1195)
    at tryResolveToken (core.js:1140)
    at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:1035)
    at resolveToken (core.js:1195)
    at tryResolveToken (core.js:1140)
    at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:1035)
    at resolveNgModuleDep (core.js:8071)
    at NgModuleRef_.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef_.get (core.js:8759)
    at resolveDep (core.js:9124)

2、可能原因是我服务中内容删除的原因,小括号中的内容

@Injectable({
  providedIn: 'root'
})

删除的原因见:https://blog.csdn.net/lich_12345/article/details/80638418

3、解决办法

在app\app.module.ts模块中增加注入

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';

import {AppComponent} from './app.component';
import {HeroesComponent} from './heroes/heroes.component';
import {HeroDetailComponent} from './hero-detail/hero-detail.component';
import {MessagesComponent} from './messages/messages.component';
import {MessageService} from './service/message.service';
import {HeroService} from './service/hero.service';

@NgModule({
  declarations: [
    AppComponent,
    HeroesComponent,
    HeroDetailComponent,
    MessagesComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [HeroService, MessageService],
  bootstrap: [AppComponent]
})
export class AppModule {
}

4、尝试的解决办法

在app\heroes\heroes.component.ts组件中增加
import {Component, OnInit} from '@angular/core';
import {Hero} from '../hero';
import {HeroService} from '../service/hero.service';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css'],
  providers: [HeroService],
})
但是它现在提示MessageService在HeroService中注入错误,HeroService没有providers属性,所以没有写在组件,而是直接把它们两写在模块中

你可能感兴趣的:(angular学习)