Angular懒加载模块从共享库中获取单独的服务实例
创始人
2024-10-27 22:00:53
0次

为了解决这个问题,我们需要在共享模块中提供一个服务提供程序,以确保所有懒加载模块使用相同的服务实例。

首先,在共享模块中创建一个服务:

shared.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class SharedService {
  constructor() { }
  
  // Your service methods here
}

接下来,在共享模块中导出ServiceProvider:

shared.module.ts

import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedService } from './shared.service';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [],
  exports: []
})
export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [SharedService]
    };
  }
}

现在,我们可以将SharedModule的forRoot方法添加到应用程序的根模块中:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { SharedModule } from './shared/shared.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    SharedModule.forRoot(),
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

现在,我们可以将SharedService添加到懒加载模块的providers数组中:

lazy.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { LazyComponent } from './lazy.component';
import { SharedService } from '../shared/shared.service';

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild([{
      path: '',
      component: LazyComponent
    }])
  ],
  declarations: [LazyComponent],
  providers: [SharedService]
})
export class LazyModule { }

这样,我们就保证了懒加载模块使用与共享模块相同的服务实例。

相关内容

热门资讯

科技介绍,德扑之星插件视频,w... 科技介绍,德扑之星插件视频,wpk有挂吗攻略(总是真的有辅助挂)是一款可以让一直输的玩家,快速成为一...
玩家必看科普,德州辅助软件,智... 德州辅助软件AI 游戏攻略黑科技上线本地缓存功能,离线查阅能力开挂。提前下载对应游戏攻略数据包,断网...
玩家必备科技,wepoker作... 玩家必备科技,wepoker作弊挂是真的吗,微扑克透视软件绝活(最初真的有辅助器)AI 是一款可以让...
玩家必看教程!,wepoker... 一款 AI 游戏攻略黑科技工具上线,查攻略效率直接开挂。它整合版本更新、装备搭配、BOSS 打法、牌...
详细说明,德州牌面分析器最新版... 详细说明,德州牌面分析器最新版本更新内容,WePoKer透视是真的吗手册(最初是有辅助);近期一款 ...
科技介绍,wepoker有挂吗... 您好,wepoker有挂吗透视知乎这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302...
一起来探讨,wepoker原来... 一起来探讨,wepoker原来有挂,AApoker透视讲义(往昔存在有透视)是一款可以让一直输的玩家...
重大来袭,德州wpk开挂辅助软... 您好:德州wpk开挂辅助软件这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用...
新2025教程,wepoker... 新2025教程,wepoker如何开透视,AApoker是不是有挂秘籍(一向是有开挂)AI 智能体黑...
重大消息,微扑克发牌规律性,W... 重大消息,微扑克发牌规律性,WePoKer开挂脚本烘培(总是是真的有辅助);近期一款 AI 黑科技工...