如何通过Injection Token将组件布尔值注入到服务中
解决方案
步骤1:定义注入令牌
首先创建一个专属注入令牌,用于传递isRecon布尔值:
import { InjectionToken } from '@angular/core'; export const IS_RECON = new InjectionToken<boolean>('标识是否为Recon模式的布尔值');
步骤2:在ScopedInjector中注入令牌值
因为isRecon原本就来自路由data.parameters,直接在ScopedInjectorComponent创建子注入器时添加该令牌的提供者,确保服务能在同一作用域内获取到值:
import { Component, OnInit, ViewContainerRef, ComponentFactoryResolver, Injector } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { IS_RECON } from './path-to-your-token-file'; // 替换为实际文件路径 @Component({ selector: 'app-scoped-injector', template: '' }) export class ScopedInjectorComponent implements OnInit { constructor( private route: ActivatedRoute, private vcr: ViewContainerRef, private cfr: ComponentFactoryResolver, private parentInjector: Injector ) {} ngOnInit() { const scopedData = this.route.snapshot.data as ScopedInjectorData<any>; const { component, parameters, providers } = scopedData; // 构建包含IS_RECON的子注入器 const childInjector = Injector.create({ parent: this.parentInjector, providers: [ ...(providers || []), { provide: IS_RECON, useValue: parameters.isRecon } // 直接传入路由参数中的isRecon ] }); // 创建并挂载目标组件 const componentFactory = this.cfr.resolveComponentFactory(component); const componentRef = this.vcr.createComponent(componentFactory, undefined, childInjector); // 传递Input参数给组件 Object.assign(componentRef.instance, parameters); } }
步骤3:在服务中注入令牌
修改CaseTileConfigurationService的构造函数,注入定义好的IS_RECON令牌:
import { Injectable, Inject, forwardRef } from '@angular/core'; import { IS_RECON } from './path-to-your-token-file'; // 替换为实际文件路径 // 其他必要导入... @Injectable() export class CaseTileConfigurationService { constructor( @Inject(forwardRef(() => CASE_SEARCH_SERVICE_CONFIGURATION_SERVICE)) private readonly configurationService: BaseCaseDataSourceConfigurationService, @Inject(forwardRef(() => ACCESS_AREA_SERVICE)) private readonly accessAreaService: BaseAccessAreaService, private _iStaticService: InvestigationsStaticDataService, @Inject(IS_RECON) public readonly isRecon: boolean // 注入isRecon值 ) { // 此处可直接使用this.isRecon } }
备选方案:组件级提供令牌
如果不想修改ScopedInjectorComponent,也可以在CaseTileComponent内部提供令牌:
import { Component, Input, forwardRef } from '@angular/core'; import { IS_RECON } from './path-to-your-token-file'; @Component({ selector: 'app-case-tile', templateUrl: './case-tile.component.html', styleUrls: ['./case-tile.component.css'], providers: [ { provide: IS_RECON, useFactory: (component: CaseTileComponent) => component._isRecon, deps: [forwardRef(() => CaseTileComponent)] } ] }) export class CaseTileComponent { private _isRecon = false; @Input() set isRecon(isRecon: boolean) { this._isRecon = isRecon; } }
这种方式下,CaseTileConfigurationService必须和CaseTileComponent处于同一注入作用域(比如组件级提供服务),才能正确获取到值。
内容的提问来源于stack exchange,提问作者tlq
相关产品推荐
相关产品推荐

