Skip to main content

New Way of Providing Shared Instance of a Service in Angular 6

Angular 6 is out and I recently posted a migration guide to upgrade Angular 5 app to Angular 6 with Visual Studio 2017. Though it’s a major release, but mainly focused on better tooling for improving the upgrading and adding new libraries a lot easier. There are some new features in Angular 6 and one of them is an alternate way of providing shared instance of a service in Angular 6.

Below is a familiar piece of code to make a service available to the entire application. We add it to providers[] in the AppModule.

// data.service.ts
export class DataService { ... }

// In app.module.ts
import { DataService } from './path/to/data.service';

@NgModule({
  declarations: [...],
  providers: [DataService],
  bootstrap: [AppComponent]
})
export class AppModule {}

Well, this still works in Angular 6. Angular 6 provides an alternate way to make the service available to the entire application.

// data.service.ts
@Injectable({
  providedIn: 'root',
})
export class DataService { ... }

// In app.module.ts
@NgModule({
  declarations: [...],
  providers: [], // No need to add service here.
  bootstrap: [AppComponent]
})
export class AppModule {}

Did you notice something new in the above code? Well, the new part is the providedIn metadata value set to ‘root’ inside @Injectable() statement.

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

When you provide the service at the root level, Angular creates a single, shared instance of the service and injects into any class that asks for it. providedIn: 'root' specifies that the service should be provided in the root injector.

If you want to learn all of Angular, I want to personally recommend ng-book as the single-best resource out there. You can get a copy here.

Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.

PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee

One thought to “New Way of Providing Shared Instance of a Service in Angular 6”

Leave a Reply

Your email address will not be published. Required fields are marked *