POV
POV

Reputation: 12015

How to make service is global in library Angular?

I have separated library in Angular project. This library has service MapLibraryService.

import { ReonMapApi } from "./map-api";

export class MapLibraryService {
  private readonly mapConfig = { key: "k123456_78" };

}

It was registed in module of library:

@NgModule({
  declarations: [MapLibraryComponent, MenuToolsComponent],
  imports: [],
  exports: [MapLibraryComponent],
  providers: nMapLibraryService]
})
export class MapLibraryModule {}

When in another part application I try to get instance of this service:

export class MapControlsComponent implements OnInit {
  constructor(private reonMapLibraryService: MapLibraryService) {
}

It returns me another instance of MapLibraryService

Upvotes: 2

Views: 5278

Answers (4)

raheel shahzad
raheel shahzad

Reputation: 65

Two ways to make a service global in angular.

1) Add a line in your service

@Injectable({
  providedIn: 'root',
})

export class MapLibraryService {
  private readonly mapConfig = { key: "k123456_78" };

}

OR

2) register service in app.module.ts:

providers: [MapLibraryService]

Upvotes: 0

spnq
spnq

Reputation: 31

If I understand you correctly, you need to decorate your service with

@Injectable({
  providedIn: 'root',
})

Read more about singletons here

Also check answer about providedIn: 'platform', but it depends on angular version of your app.

Upvotes: 2

Chellappan வ
Chellappan வ

Reputation: 27409

If you are using angular 9 release candidate version you can use platform injector, Which will provide special singleton shared by all applications on the page.

@Injectable({
  providedIn: 'platform'
})

For More Info

Upvotes: 3

uminder
uminder

Reputation: 26170

You should decorate your service class with @Injectable

@Injectable({
  providedIn: 'root'
})
export class MapLibraryService {
  private readonly mapConfig = { key: "k123456_78" };

}

Upvotes: 2

Related Questions