Lazy loading : Observable not subscribed

北战南征 提交于 2019-12-22 09:23:22

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/47134412/lazy-loading-observable-not-subscribed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!