rob_hicks
rob_hicks

Reputation: 1744

How to access Angular2 root injected Service in Component?

According to http://victorsavkin.com/post/126514197956/dependency-injection-in-angular-1-and-angular-2, application-wide services can be added to the root injector using something like this:

bootstrap(App, [UserService, LoginService]

And then can be accessed in child components like this:

class A {
  constructor(userService: UserService) {
    
  }
}

However, an exception results, complaining the parameters can't be resolved and suggesting to make sure they have proper type or annotation.

What is the right way to inject application-wide services and access them in child components?

Upvotes: 1

Views: 1423

Answers (1)

Tiffany Chow
Tiffany Chow

Reputation: 11

If the child component is in a separate file, make sure you still import the service in.

import {UserService} from '../../services/UserService';

@Component({
     // don't add UserService in providers here
})

class A {
    userService: UserService;
    constructor(userService: UserService) { 
        this.userService = userService;
    }
}

Upvotes: 1

Related Questions