Search code examples
angularangular-routerangular-providers

Destroy Angular Service when route change


I have a complexe module called MyPageModule importing several modules which provides Service with following annotation @Injectable( { providedIn: 'root' } ).

This module is imported by lazy loading like this:

// AppRoutingModule
...
 {
    path: 'my-page',
    loadChildren: './lazy-loader-modules/lazy-loader-mypage/lazy-loader-mypage.module#LazyLoaderMyPageModule'
 }

...
// LazyLoaderMyPageModule
@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    MyPageModule
  ]
})
export class LazyLoaderMyPageModule { }

Behavior that I want (not the case actually): When url is different of /my-page/*, I'd like that all services imported by MyPageModule are destroyed.

How can I do this ?


Solution

  • Create a root component on your lazy loaded module with a router-outlet and add providers on component metadata

    @Component({
      selector: 'app-my-page-root',
      template: '<router-outlet></router-outlet>',
      styleUrls: ['./my-page-root.component.scss'],
      providers:[MyPageService, MyPageOtherService]
    }) 
    class MyPageRootComponent {}
    

    Change your lazy loaded module routes to be:

    const routes= [
     { 
        path: '',
        component: MyPageRootComponent
        children: [
          // all of your routes
        ]
     }
    ]
    

    When MyPageRootComponent is destroyed all of your services will be destroyed.

    Edit:

    StackBlitz: https://stackblitz.com/edit/lazy-load-destory-services