@@ -96,6 +96,7 @@ export function resolveComponent(target: { new (...args: []): any }) {
9696 resolveProviders ,
9797 parent ,
9898 )
99+ console . log ( 11111 , injector )
99100 if ( options ?. globalStore ) {
100101 // 如果作为全局的服务,则注入到根上面
101102 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
@@ -162,7 +163,7 @@ export function resolveDependencies(inputs: Provider[]) {
162163export function getCurrentInjector ( ) : ReflectiveInjector {
163164 const instance = getCurrentInstance ( )
164165 // @ts -ignore
165- return instance . provides [ InjectorKey ] || inject ( InjectorKey )
166+ return instance ? .provides [ InjectorKey ] || inject ( InjectorKey )
166167}
167168/** 手动创建当前注射器, 只能用在 setup 中 */
168169export function createCurrentInjector (
@@ -205,4 +206,38 @@ function injectService(token: any, notFoundValue?: any) {
205206 return currentInjector . get ( token , notFoundValue )
206207}
207208
208- export { injectService }
209+ interface Constructable {
210+ // eslint-disable-next-line @typescript-eslint/ban-types
211+ constructor : Function
212+ }
213+ function provideService < T extends Constructable > ( ...service : T [ ] ) {
214+ const instance = getCurrentInstance ( ) !
215+ // @ts -ignore
216+ let injector : ReflectiveInjector
217+ if ( Reflect . has ( instance , InjectorKey as symbol ) ) {
218+ // @ts -ignore
219+ injector = instance . provides [ InjectorKey ]
220+ }
221+ // @ts -ignore
222+ if ( ! injector ) {
223+ injector = ReflectiveInjector . resolveAndCreate ( [ ] , inject ( InjectorKey ) )
224+ // @ts -ignore
225+ instance . provides [ InjectorKey ] = injector
226+ }
227+
228+ ReflectiveInjector . resolve (
229+ service . map ( ( k ) => ( { provide : k . constructor , useValue : k } ) ) ,
230+ ) . forEach ( ( provider , i ) => {
231+ // @ts -ignore
232+ const index = injector . _providers . length
233+ // @ts -ignore
234+ injector . _providers [ index ] = provider
235+ // @ts -ignore
236+ injector . keyIds [ index ] = provider . key . id
237+ // @ts -ignore
238+ injector . objs [ index ] = provider [ i ]
239+ } )
240+ return injector
241+ }
242+
243+ export { injectService , provideService }
0 commit comments