我希望在angular组件的运行时在两个不同的服务中解析一个令牌。我将令牌添加到模块中的providers数组中,如下所示。
providers: [{
provide: ACCOUNT_SERVICE,
useClass: AccountServiceOne
},
{
provide: ACCOUNT_SERVICE,
useClass: AccountServiceTwo
}]
我想在两个不同的类中使用ACCOUNT_SERVICE
令牌。在AccountServiceA
中,我希望令牌解析为AccountServiceOne
,在AccountServiceB
中,我希望令牌解析为AccountServiceTwo
。见下文.
@Injectable({ providedIn: 'root' })
export class AccountServiceA {
public constructor(
@Inject(ACCOUNT_SERVICE)
) {
}
}
@Injectable({ providedIn: 'root' })
export class AccountServiceB {
public constructor(
@Inject(ACCOUNT_SERVICE)
) {
}
}
有可能在运行时解决这个问题吗?
假设你有FirstModule
@Injectable()
export class AccountServiceOne {
constructor() {}
public someMethod() {
console.log('service one method');
}
}
@Injectable()
export class AccountServiceA {
constructor(
public accountService: AccountService
) {}
}
@NgModule({
providers: [
AccountServiceOne,
AccountServiceA,
{
provide: AccountService,
useClass: AccountServiceOne
}]
})
export class FirstModule {
}
然后是SecondModule
@Injectable()
export class AccountServiceTwo {
constructor() {}
public someMethod() {
console.log('service two method');
}
}
@Injectable()
export class AccountServiceB {
constructor(
public accountService: AccountService
) {}
}
@NgModule({
providers: [
AccountServiceTwo,
AccountServiceB,
{
provide: AccountService,
useClass: AccountServiceTwo
}]
})
export class SecondModule {
}
则AccountServiceA
和AccountServiceB
中的accountService
会相应解析为AccountServiceOne
和AccountServiceTwo
。