Skip to content

Commit

Permalink
feat: add provideService
Browse files Browse the repository at this point in the history
  • Loading branch information
agileago committed Oct 14, 2024
1 parent 27f24e8 commit 044aa65
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
4 changes: 3 additions & 1 deletion example/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ class Child extends VueComponent<ChildProps> {
}
}

@Component({ providers: [RouterStartService] })
@Component({
providers: [RouterStartService],
})
class App extends VueComponent {
constructor(private a: RouterStartService) {
super()
Expand Down
39 changes: 37 additions & 2 deletions src/di/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ export function resolveComponent(target: { new (...args: []): any }) {
resolveProviders,
parent,
)
console.log(11111, injector)
if (options?.globalStore) {
// 如果作为全局的服务,则注入到根上面
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
Expand Down Expand Up @@ -162,7 +163,7 @@ export function resolveDependencies(inputs: Provider[]) {
export function getCurrentInjector(): ReflectiveInjector {
const instance = getCurrentInstance()
// @ts-ignore
return instance.provides[InjectorKey] || inject(InjectorKey)
return instance?.provides[InjectorKey] || inject(InjectorKey)
}
/** 手动创建当前注射器, 只能用在 setup 中 */
export function createCurrentInjector(
Expand Down Expand Up @@ -205,4 +206,38 @@ function injectService(token: any, notFoundValue?: any) {
return currentInjector.get(token, notFoundValue)
}

export { injectService }
interface Constructable {
// eslint-disable-next-line @typescript-eslint/ban-types
constructor: Function
}
function provideService<T extends Constructable>(...service: T[]) {
const instance = getCurrentInstance()!
// @ts-ignore
let injector: ReflectiveInjector
if (Reflect.has(instance, InjectorKey as symbol)) {
// @ts-ignore
injector = instance.provides[InjectorKey]
}
// @ts-ignore
if (!injector) {
injector = ReflectiveInjector.resolveAndCreate([], inject(InjectorKey))
// @ts-ignore
instance.provides[InjectorKey] = injector
}

ReflectiveInjector.resolve(
service.map((k) => ({ provide: k.constructor, useValue: k })),
).forEach((provider, i) => {
// @ts-ignore
const index = injector._providers.length
// @ts-ignore
injector._providers[index] = provider
// @ts-ignore
injector.keyIds[index] = provider.key.id
// @ts-ignore
injector.objs[index] = provider[i]
})
return injector
}

export { injectService, provideService }
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export {
getCurrentInjector,
createCurrentInjector,
injectService,
provideService,
} from './di'
export type { ComponentOptions } from './di'
export type {
Expand Down

0 comments on commit 044aa65

Please sign in to comment.