Destroy Angular Service when route change

angular service lifecycle
when does angular destroy components
destroy service when leaving module
ngondestroy not getting called

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 ?

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

Check if ngOnDestroy is called on a route change - angular - html, Check if ngOnDestroy is called on a route change - angular I created a boolean called inNavigation in my prompt.service.ts 2.Then, in the service constructor,  Detecting whenever a route change happens in your application can be very useful for a multitude of reasons. For instance you may wish to store form data in a cookie in case they accidentally clicked on something they didn’t mean to. In Angular 2 detecting this route change is relatively simple.

Use

  providedIn: UserModule,

Read more

destructor option for service providers · Issue #11228 · angular , For our case, we wished for a service to be destroyed once navigating @mlc-​mlapis When my route changes to leave a lazy loaded module. above most of solutions correct , but i am facing issue this emit multiple times 'Navigation emit' event.when i was change any route this event is triggered. So hear is the complete solution for Angular 6.

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.

In-app navigation with routing, Provides a module to replace or remove when testing the application. Provides a well-known location for routing service providers such as guards and resolvers. If you add providedIn: root, the service's lifetime is coupled to your app.module.ts. You can add the service to your feature module and remove the providedIn property. If the module then gets destroyed, the service will, too and you can unsubscribe in the onDestroy method.

Upgrading from AngularJS to Angular, In this example application, each controller, component, service, and filter is in its Those calls just trigger additional AngularJS change detection checks in a hybrid application. You can remove the ng-app and ng-strict-di directives from the HTML and When the Angular Router matches a route that uses AngularJS, the  OnDestroy interface is a lifecycle hook. It has a method ngOnDestroy (). It is called for cleanup logic when a component, directive, pipe or service is destroyed. ngOnDestroy () is called just before component/directive is about to be destroyed by Angular. It can be used for following purposes.

When a service got destroyed in angular - DEV, Tagged with typescript, angular, javascript. loaded services are only initialised the first time a route is loaded, an providedIn: 'root' service is  Used for AngularJS to Angular migrations. Fast and Consistent. After the previous introduction about the current state of the Angular Framework, we are now ready to get started working on our angular 7 app. Angularjs refresh data from service when route changes. Broadcasted before a route change. Angular route resolvers and controller activation.

A Deep Dive into Angular's NgOnDestroy, Called just before Angular destroys the directive/component.” As with other lifecycle methods in Angular, you can modify ngOnDestroy with async . This will allow you to make calls my.service'; import { AuthService } from '. Provided that you already have guards: Maybe inside of a route guard that is executed on the way in you can clean up/initialize the service i.e. every time user wants to go back to this component the service-s state gets zeroed out. Alternatively the service could become a provider of a service-s instead of doing the work itself.

Comments
  • When I do this, I have the error: No provider for ... even when service is in component providers
  • You need to remove the providedIn: 'root' property from the services. I've added a stackblitz with an example to the answer.
  • 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
  • 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.
  • Where is there documentation about when or even if Angular modules are destroyed?