Skip to content

Commit

Permalink
feat: 初始化未在constructor声明的服务
Browse files Browse the repository at this point in the history
  • Loading branch information
agileago committed Dec 12, 2021
1 parent 25578a7 commit 83f0ef3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
9 changes: 8 additions & 1 deletion example/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,16 @@ class HomeChild extends VueComponent<HomeChild_Props> {
)
}
}
class AService extends VueService {
constructor() {
super()
console.log('aservice init')
}
}

// 组件
@Autobind() // 绑定this 也可以放到这里
@Component({ providers: [CountService] }) // 声明自己的服务
@Component({ providers: [CountService, AService] }) // 声明自己的服务
class Home extends VueComponent {
// 构造函数注入服务,无需new
constructor(private countService: CountService) {
Expand Down
8 changes: 6 additions & 2 deletions src/di/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ export function resolveComponent(target: { new (...args: []): any }) {
if (options?.exclude?.length) {
deps = deps.filter((k) => !options.exclude?.includes(k))
}
const injector = ReflectiveInjector.resolveAndCreate(deps, parent)
const resolveProviders = ReflectiveInjector.resolve(deps)
const injector = ReflectiveInjector.fromResolvedProviders(resolveProviders, parent)
if (options?.globalStore) {
// 如果作为全局的服务,则注入到根上面
const current = getCurrentInstance()!
Expand All @@ -61,5 +62,8 @@ export function resolveComponent(target: { new (...args: []): any }) {
} else {
provide(InjectorKey, injector)
}
return injector.get(target)
const compInstance = injector.get(target)
// 处理一下providers中的未创建实例的服务
if (options?.providers?.length) resolveProviders.forEach((k) => injector.get(k.key.token))
return compInstance
}

0 comments on commit 83f0ef3

Please sign in to comment.