Search code examples
angularrxjslazy-loading

Lazy loading : Observable not subscribed


In my Angular App, I have a parent component :

console.component.html

<div class="main">
  <ibe-snackbar></ibe-snackbar>
  <router-outlet></router-outlet>
</div>

routler-outlet can load two child component. One is loaded eagerly the other one is loaded with lazy loading. Here's the routes file

console.component.routes

const ConsoleRoutes: Routes = [
  { path: 'console', component: ConsoleComponent, data: {context : CONSOLE_CONTEXT},
    children: [
      { path: "projects", component: ProjectsListComponent, data : {context : PROJECT_CONTEXT}}, --> Loaded eagerly
      { path: "projects/:projectId/users", loadChildren: "./users/users.module#UsersModule" }, ---> Loaded laziness
      { path: '', redirectTo: "projects", pathMatch: "full" },
    ]
  }
];

export const ConsoleRouting: ModuleWithProviders = RouterModule.forChild(ConsoleRoutes);

The snackbar component initialize an observable which will display a message on component when it will be called.

snackbar.service.ts

export class SnackbarService {
  private subject = new Subject<any>();
  constructor() { }

  showSnackbar(message, type) {
    // Treatment
    this.subject.next(snackbarInfos);
  }

  getSnackbarObservable(): Observable<any> {
    return this.subject.asObservable();
  }
}

sanckbar.component.ts

export class SnackbarComponent implements OnInit {

  constructor(private snackbarService: SnackbarService, private translate: TranslateService) { }

  ngOnInit() {
    this.snackbarService.getSnackbarObservable()
    .subscribe(snackbar => {
      this.snackbar = snackbar;
      this.display();
    });
  }
}

So the child component call the snackbar service which send the informations to the observable.

I noticed that the observable initialized in snackbar.component.ts is never subscribed (never called), when my child component is loaded with lazy loading...

However it works perfectly when the child component is load eargerly

Have you an idea why the RxJS observable is not called ?


Solution

  • I suspect it's because lazy loaded module has its own scope of singleton service, means there two instance of your SnackbarService. Try move the service to the highest level module like app module see if that solves the problem.