Angular no provider for NameService

后端 未结 18 1763
遇见更好的自我
遇见更好的自我 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:41

    Blockquote

    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: `
      `
    })
    export class HeroesComponent { }
    
    0 讨论(0)
  • 2020-11-30 19:42

    Shockingly, the syntax has changed yet again in the latest version of Angular :-) From the Angular 6 docs:

    Beginning with Angular 6.0, the preferred way to create a singleton services is to specify on the service that it should be provided in the application root. This is done by setting providedIn to root on the service's @Injectable decorator:

    src/app/user.service.0.ts

    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root',
    })
    export class UserService {
    }
    
    0 讨论(0)
  • 2020-11-30 19:43

    You have to use providers instead of injectables

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

    Complete code sample here.

    0 讨论(0)
  • 2020-11-30 19:43

    You could also have the dependencies declared in the bootstrap-command like:

    bootstrap(MyAppComponent,[NameService]);
    

    At least that's what worked for me in alpha40.

    this is the link: http://www.syntaxsuccess.com/viewarticle/dependency-injection-in-angular-2.0

    0 讨论(0)
  • 2020-11-30 19:44

    The error No provider for NameService is a common issue that many Angular2 beginners face.

    Reason: Before using any custom service you first have to register it with NgModule by adding it to the providers list:

    Solution:

    @NgModule({
        imports: [...],
        providers: [CustomServiceName]
    })
    
    0 讨论(0)
  • 2020-11-30 19:44

    Add it to providers not injectables

    @Component({
        selector:'my-app',
        providers: [NameService]
    })
    
    0 讨论(0)
提交回复
热议问题