[FIXED] Automatically register services in Angular

Issue

In Vue.js I use the technique with require.context as documented in in the Vue Guide

I was wondering if there’s an equivalent for this that works with Ionic Angular so I don’t have to add every single service I write into app.module.ts

Solution

From the Angular docs (https://angular.io/guide/singleton-services#using-providedin):

Beginning with Angular 6.0, the preferred way to create a singleton service is to set providedIn to root on the service’s @Injectable() decorator. This tells Angular to provide the service in the application root.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root', // <-- here!
})
export class UserService { ... }

So if you set the provideIn to root in the injectable decorator, you don’t need to add that service to the providers array of the AppModule anymore.

Keep in mind that…

using the providedIn property of the @Injectable() decorator on the service itself is preferable as of Angular 6.0 as it makes your services tree-shakable.

Answered By – sebaferreras

Answer Checked By – Gilberto Lyons (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published