简体   繁体   中英

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?

Use

  providedIn: UserModule,

Read more

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM