Reputation: 12015
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
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
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
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'
})
Upvotes: 3
Reputation: 26170
You should decorate your service class with @Injectable
@Injectable({
providedIn: 'root'
})
export class MapLibraryService {
private readonly mapConfig = { key: "k123456_78" };
}
Upvotes: 2