Angular如何重新初始化单例服务

jon*_*hin 1 angular

我有一个名为 DesignerComponent 的组件和子组件,它们共享一个名为 ProjectService 的服务,并且该服务在名为 DesignerModule 的模块中声明为提供程序,因为 DesignerComponent 和子组件必须共享 ProjectService 实例。

一切正常,但是当我转到另一个页面并返回此页面时,该服务仍然保留所有旧数据,换句话说,该服务实例永远不会重新创建。如何在离开和返回模块或页面时强制 Angular 创建一个新的服务实例,但仍然能够在子组件之间共享一个实例?

app.module.ts
@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    FormsModule,
      RouterModule.forRoot([
        { path: '', loadChildren: () => import('./site/site.module').then(u => u.SiteModule) },
        { path: 'designer', loadChildren: () => import('./designer/designer.module').then(u => u.DesignerModule), canActivate: [AuthGuard] },
        { path: 'signin', loadChildren: () => import('./login/signin/signin.module').then(u => u.SigninModule) },
        { path: 'signup', loadChildren: () => import('./login/signup/signup.module').then(u => u.SignupModule) },
    ]),
    BrowserAnimationsModule,
    StoreModule.forRoot(reducers, {
      metaReducers,
      runtimeChecks: {
        strictStateImmutability: true,
        strictActionImmutability: true,
      }
    }),
  ],
  providers: [
    ScriptService,
    ComponentLoadService,
    MessagingService,
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
  ],
  bootstrap: [AppComponent],
})
export class AppModule { }

designer.module.ts
@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild([
      { path: ':id', component: DesignerComponent }
    ]),
    AngularSplitModule.forRoot(),
    ...
  ],
  declarations: [
     DesignerComponent,
     DesignerMenuComponent,
     ...
  ]
  providers: [
    ProjectService,
    ...
  ]
})
export class DesignerModule { }

project.service.ts
@Injectable()
export class ProjectService{
   private historyModule: ProjectUndoRedo[] = []; // This value still hold old data after going to another page and coming back. I want this service to be reinitialized
}

designer.component.ts
export class DesignerComponent{
   constructor(public projectService: ProjectService) {
      // When this constructor is called, projectSerivce instance is the old instance.
   }
}

designer-menu.component.ts
export class DesignerMenuComponent{
   constructor(public projectService: ProjectService) {
      // When this constructor is called, projectSerivce instance is the old instance.
   }
}
Run Code Online (Sandbox Code Playgroud)

pix*_*its 10

添加到 NgModule 的任何服务都向根注入器(或用于延迟加载路由模块的延迟注入器)注册。因此,服务范围是整个应用程序,并保留其价值。

如果您想缩小范围,请改为向组件注册服务:

@NgComponent({
    selector: 'app-designer',
    providers: [
       ProjectService
    ]
})
export class DesignerComponent {
}
Run Code Online (Sandbox Code Playgroud)

这将向组件注入器(分层的)注册服务,并且其范围仅限于所注册组件的生命周期。

当路由发生变化,并且设计器组件被另一个组件替换时,它将重新创建并重新初始化该组件(以及它注册的任何提供程序)。

注意:由于服务的生命周期与组件的生命周期密切相关,因此如果需要,您还可以在 DesignerComponentngOnInit中执行服务的初始化例程和清理例程ngOnDestroy