5

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 ?

Kael
  • 858
  • 9
  • 21

3 Answers3

5

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

Tiago Viegas
  • 181
  • 6
  • When I do this, I have the error: `No provider for ... ` even when service is in component providers – Kael Oct 03 '19 at 15:05
  • You need to remove the providedIn: 'root' property from the services. I've added a stackblitz with an example to the answer. – Tiago Viegas Oct 03 '19 at 20:38
  • My prob comes with MatDialog which are in entryComponent, so out of scope. So I need to pass service in Data to resolve the problem – Kael Oct 31 '19 at 16:30
0

Use

  providedIn: UserModule,

Read more

dota2pro
  • 7,220
  • 7
  • 44
  • 79
0

Simply provide your services into the module.

Remove the

{ providedIn: 'root' }

And use this

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    MyPageModule
  ],
  providers: [MyServiceOne, MyServiceTwo]
})

Everytime the module gets destroyed, the services follow.

  • Already do this, the service is always active. For exemple, my service store a GUID set byMyPageComponent at init. I go to "/example" then return to "/my-page", the older GUID is always present. – Kael Oct 03 '19 at 14:30
  • Where is there documentation about when or even if Angular modules are destroyed? – tedw Jan 09 '20 at 17:56