延迟加载:可观察的未订阅 [英] Lazy loading : Observable not subscribed

查看:76
本文介绍了延迟加载:可观察的未订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular应用中,我有一个父组件:

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可以加载两个子组件.一个被热切地加载,另一个被延迟加载.这是路线文件

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.

我注意到,当我的子组件加载为延迟加载时,snackbar.component.ts中的可观察变量初始化从未被订阅(从未调用).

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

您知道为什么未调用RxJS的可观察对象吗?

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

推荐答案

我怀疑这是因为延迟加载的模块具有自己的单例服务范围,这意味着您的SnackbarService有两个实例.尝试将服务移至最高级别的模块(如应用程序模块),看看是否可以解决问题.

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.

这篇关于延迟加载:可观察的未订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆