Lazy loading : Observable not subscribed

Viewed 4553

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 ?

3 Answers

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.

Lazy loading would not affect the subscription to any service or observable. The problem would be related to the type of Subject you have used in the service.

I think you should be using ReplaySubject instead of Subject

Related