Angular no provider for NameService

后端 未结 18 1888
遇见更好的自我
遇见更好的自我 2020-11-30 18:44

I\'ve got a problem loading a class into an Angular component. I\'ve been trying to solve it for a long time; I\'ve even tried joining it all in a single file. What I have i

18条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 19:34

    You need to add it to providers array, which includes all depency on your component.

    Look at this section in angular documentation:

    Registering providers in a component

    Here's a revised HeroesComponent that registers the HeroService in its providers array.

    import { Component } from '@angular/core';
    
    import { HeroService } from './hero.service';
    
    @Component({
      selector: 'my-heroes',
      providers: [HeroService],
      template: `
      

    Heroes

    ` }) export class HeroesComponent { }

    When to use NgModule versus an application component

    On the one hand, a provider in an NgModule is registered in the root injector. That means that every provider registered within an NgModule will be accessible in the entire application.

    On the other hand, a provider registered in an application component is available only on that component and all its children.

    Here, the APP_CONFIG service needs to be available all across the application, so it's registered in the AppModule @NgModule providers array. But since the HeroService is only used within the Heroes feature area and nowhere else, it makes sense to register it in the HeroesComponent.

    Also see "Should I add app-wide providers to the root AppModule or the root AppComponent?" in the NgModule FAQ.

    So in your case, simply change injectables to providers like below:

    @Component({
      selector: 'my-app',
      providers: [NameService]
    })
    

    Also in the new versions of Angular, @View and some other stuffs gone.

    For more info ,visit here.

提交回复
热议问题