Maks K
Maks K

Reputation: 3914

Issue with globally visible service in Angular 2

I am tying to make service, which would be visible without importing in component.

My bootstrap function:

export function main(initialHmrState?: any): Promise<any> {
  console.log(APP_PROVIDERS);
  return bootstrap(App, [
    ...PLATFORM_PROVIDERS,
    ...ENV_PROVIDERS,
    ...APP_PROVIDERS
  ])
  .then(decorateComponentRef)
  .catch(err => console.error(err));
}

App providers definition:

export * from './app.component';
export * from './user.state';
export * from './app.service';

import { UserState } from './user.state';
import { AppState } from './app.service';

// Application wide providers
export const APP_PROVIDERS = [
  UserState,
  AppState
];

And i can not call it in components constructor

 constructor( private userState: UserState ) {} 

How i can fix my problem?

Upvotes: 0

Views: 72

Answers (2)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657546

Either by importing it or by using a string token or OpaqueToken and `@Inject()

export const APP_PROVIDERS = [
  {provide: 'UserState', useClass: UserState},
  AppState
];
constructor(@Inject('UserState') private userState: any ) {} 

Upvotes: 1

Thierry Templier
Thierry Templier

Reputation: 202216

There are two parts:

  • Defining the provider names using types
  • Using the types for injection

In both cases, you need to import corresponding types. Otherwise, they won't be resolved...

Note that it's not mandatory to use types for dependency injection. You could eventually use OpaqueTokens:

export const SOME_TOKEN = new OpaqueToken('sometoken');
let provider = { provide: token, useClass: UserState };

and use it:

 constructor( @Inject(SOME_TOKEN) private userState: UserState ) {} 

But in this case, you also need to import the opaque token...

Upvotes: 1

Related Questions