Search code examples
angulardependency-injectioninjectableangular2-providersng-modules

Do app.module providers and components share the same instance of an Injectable?


When I add the injectable CameraChannelService into ngModule's provider array:

import { CameraChannelService } from './camera-channel.service';


@NgModule({
  declarations: [
    AppComponent,
    BabylonWallpaperDirective,
    MenuComponent,
    WorksComponent,
    LabsComponent,
    ProfileComponent,
    ActionBtnComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing
  ],
  providers: [
    CameraChannelService
  ],
  bootstrap: [AppComponent]
})

Does it create a new instance for just that component? when I inject it into one of the NgModules declarations components?

import { Component, OnInit } from '@angular/core';
import {CameraChannelService} from '../camera-channel.service';
@Component({
  selector: 'app-works',
  templateUrl: './works.component.html',
  styleUrls: ['./works.component.scss'],
  providers: [CameraChannelService]
})
export class WorksComponent implements OnInit {

  constructor(private cameraChannel: CameraChannelService) { }

  ngOnInit() {
    console.log(this.cameraChannel);
  }
}

Solution

  • Yes...

    If you add providers: [CameraChannelService] to Component's @Component decorator, it creates a new instance scoped to that component only.

    If you declare providers: [CameraChannelService] in @NgModule that creates an instance scoped to entire application.

    So if you want to use same instance throughout application then only declare service in @NgModule decorator of AppModule.ts file and don't declare it again in Component's @Component decorator


    Side Note : Rather than declaring service to @NgModule,use CoreModule to declare service and import it into AppModule. So, later if you want to configure your service, you will be able to configure your service.