Angular2 Beta dependency injection

前端 未结 3 887
野性不改
野性不改 2021-01-14 06:26

I have a NavBar Component which loads the QApi Service, the QApi Service loads the UserService, but I get the following error:

EXCEPTION: No provider for Use         


        
相关标签:
3条回答
  • 2021-01-14 06:37

    List the services in your bootstrap call (wherever you are handling that). Something like the following should work:

    bootstrap(App, [UserService, QApi, COMMON_DIRECTIVES, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, HTTP_PROVIDERS]); 
    providers// directives added here are available to all children
    

    Then you will have a single instance of each of those services available to the rest of your application.

    0 讨论(0)
  • 2021-01-14 06:50

    In fact both previous responses are true! ;-)

    You need to define the services:

    • Application level. Within the second parameter of the bootstrap function. It contains the list of the providers that are available for the whole application.

      bootstrap(App, [UserService, QApi, ...]);
      
    • Component level. Within the providers attribute of the Component annotation. In this case, this is only configured for this component and you need to define this for each component where the QApi service.

      @Component({
        selector: 'nav-bar',
        template: `Test NavBar`,
        providers: [QApi, UserService]
      })
      

    You also mix things. I mean you can put the UserService provider at the application level and QApi at the component level. In fact what is important is that Angular can find providers for all the involved elements in the processing chaining (with dependency injection). They can come from either component level (1st) or application level (2nd).

    Hope that it gives you some additional hints following alexpods and MichaelOryl great answers ;-)

    Thierry

    0 讨论(0)
  • 2021-01-14 07:03

    Add UserService to the component providers:

    @Component({
        selector: 'nav-bar',
        template: `Test NavBar`,
        providers: [QApi, UserService] // <- add UserService here
    })
    export class NavBarComponent { /* ... */ }
    

    Here are two good articles to better understand Angular2 Dependency Injection:

    • blog.thoughtram.io: Dependency Injection in Angular2
    • blog.thoughtram.io: Injecting services in services in Angular 2
    0 讨论(0)
提交回复
热议问题