在angular中将单个令牌解析为多个服务



我希望在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 {
}

AccountServiceAAccountServiceB中的accountService会相应解析为AccountServiceOneAccountServiceTwo

相关内容

  • 没有找到相关文章

最新更新