要在Angular 8中在懒加载模块之间共享组件状态,可以使用共享模块和服务来实现。下面是一个代码示例:
首先,创建一个共享模块,例如SharedModule,用于导入和导出需要共享的组件和服务:
// shared.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedComponent } from './shared.component';
@NgModule({
declarations: [SharedComponent],
imports: [CommonModule],
exports: [SharedComponent]
})
export class SharedModule { }
然后,在需要共享组件状态的懒加载模块中导入SharedModule,并在需要使用共享组件的组件中使用该组件:
// lazy.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../shared/shared.module';
import { LazyComponent } from './lazy.component';
@NgModule({
declarations: [LazyComponent],
imports: [
CommonModule,
SharedModule
]
})
export class LazyModule { }
// lazy.component.ts
import { Component } from '@angular/core';
import { SharedComponent } from '../shared/shared.component';
@Component({
selector: 'app-lazy',
template: `
Lazy Component
`
})
export class LazyComponent {
// 使用共享组件状态
}
这样,在懒加载模块中可以使用SharedComponent,并且可以共享组件的状态。
如果要在不同的懒加载模块之间共享组件状态,可以创建一个共享服务来存储和管理状态。在SharedModule中提供该服务:
// shared.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SharedService {
// 共享的状态和方法
}
// shared.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../shared/shared.module';
import { SharedComponent } from './shared.component';
import { SharedService } from './shared.service';
@NgModule({
declarations: [SharedComponent],
imports: [CommonModule],
exports: [SharedComponent],
providers: [SharedService]
})
export class SharedModule { }
然后,在需要使用共享状态的组件中注入SharedService,并使用该服务进行状态的存储和访问:
// lazy.component.ts
import { Component } from '@angular/core';
import { SharedService } from '../shared/shared.service';
@Component({
selector: 'app-lazy',
template: `
Lazy Component
`
})
export class LazyComponent {
constructor(private sharedService: SharedService) { }
updateState() {
this.sharedService.updateState();
}
}
这样,不同的懒加载模块中的组件可以共享同一个SharedService的状态。
上一篇:Angular 8: 在HTML中根据组件动态设置formControlName
下一篇:Angular 8: 在overflow:auto中HammerJs的swipeRight和swipeLeft不起作用