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 { }

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

相关内容

热门资讯

透视存在!wepoker透视脚... 透视存在!wepoker透视脚本苹果版,wepoker辅助脚本,黑科技教程(原本是有挂);wepok...
透视模拟器!aapoker辅助... 透视模拟器!aapoker辅助功能,wepoker正确养号方法,高科技教程(从前有挂)1、这是跨平台...
透视神器!aapoker辅助插... 透视神器!aapoker辅助插件工具,aapoker透视脚本,透明教程(先前真的有挂)是一款可以让一...
透视中牌率!aapoker脚本... 透视中牌率!aapoker脚本怎么用,hhpoker开挂教程,微扑克教程(总是是真的有挂);(需添加...
透视ai代打!德普之星怎么作弊... 透视ai代打!德普之星怎么作弊,wepokerplus开挂,切实教程(原来真的有挂);实战中需综合运...
透视软件!德普之星透视辅助插件... 1、透视软件!德普之星透视辅助插件,哈糖大菠萝攻略,AI教程(都是真的是有挂);详细教程。2、德普之...
透视好友!wpk辅助器是真的吗... 透视好友!wpk辅助器是真的吗,wepoker黑侠辅助器,大神讲解(果然是真的有挂)是一款可以让一直...
透视规律!wepoker底牌透... 透视规律!wepoker底牌透视脚本app,wepoker透视脚本是什么,必备教程(最初真的有挂);...
透视真的!wepoker透视脚... 透视真的!wepoker透视脚本网页,wpk作弊最怕三个东西,细节方法(其实是有挂)关于wepoke...
透视代打!德普之星透视辅助io... 1、透视代打!德普之星透视辅助ios,pokermaster修改器,曝光教程(都是有挂)。2、德普之...