Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular service providedIn VS forRoot

Tags:

angular

I'd like to know if these two blocks of code are equivalent or not.

Can I use providedIn with the same result of forRoot?

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor() { }
}

vs

@Injectable()
export class MyService {
  constructor() { }
}

@NgModule({
  imports: []
})
export class MyModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: MyModule,
      providers: [
        MyService
      ]
    };
  }
}

@NgModule({
  imports: [
    MyModule.forRoot()
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

[I would still keep my MyModule for single use with the providedId singleton services]

like image 675
user3887366 Avatar asked Nov 11 '18 18:11

user3887366


People also ask

What is the difference between providedIn and providers in Angular?

providedIn is the new Angular way of doing DI. providedIn was brought since Angular 6. The official name is "Tree-shakeable providers" - instead of module providing all its services, it is now the service itself declaring where it should be provided.

What is providedIn in Angular service?

The providedIn allow us to specify how Angular should provide the dependency in the service class itself instead of in the Angular Module. It also helps to make the service tree shakable i.e. remove the service from the final bundle if the app does not use it.

What is forRoot in Angular?

The forRoot static method is the method that configures the root routing module for your app. When you call RouterModule. forRoot(routes) , you are asking Angular to instantiate an instance of the Router class globally.

How do you prevent to use a service as a singleton in Angular?

There are multiple ways to prevent this: Use the providedIn syntax instead of registering the service in the module. Separate your services into their own module. Define forRoot() and forChild() methods in the module.


2 Answers

Using providedIn vs providers[]:

  1. providedIn is the new Angular way of doing DI. providedIn was brought since Angular 6

  2. The official name is "Tree-shakeable providers" - instead of module providing all its services, it is now the service itself declaring where it should be provided

  3. Using providedIn: 'root' removes the need to import the library module at all, we can simply inject needed services and it just works

like image 53
TheUnreal Avatar answered Oct 16 '22 13:10

TheUnreal


Yes, forRoot and provideIn both are equivalent since both will create the only and only one singleton for the app. Even though it being loaded in lazy loaded component.

Refer this nice article on it - https://medium.com/@chrishouse/when-to-use-angulars-forroot-method-400094a0ebb7

like image 7
Sunil Singh Avatar answered Oct 16 '22 14:10

Sunil Singh