@@ -96,6 +96,7 @@ export function resolveComponent(target: { new (...args: []): any }) {
96
96
resolveProviders ,
97
97
parent ,
98
98
)
99
+ console . log ( 11111 , injector )
99
100
if ( options ?. globalStore ) {
100
101
// 如果作为全局的服务,则注入到根上面
101
102
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
@@ -162,7 +163,7 @@ export function resolveDependencies(inputs: Provider[]) {
162
163
export function getCurrentInjector ( ) : ReflectiveInjector {
163
164
const instance = getCurrentInstance ( )
164
165
// @ts -ignore
165
- return instance . provides [ InjectorKey ] || inject ( InjectorKey )
166
+ return instance ? .provides [ InjectorKey ] || inject ( InjectorKey )
166
167
}
167
168
/** 手动创建当前注射器, 只能用在 setup 中 */
168
169
export function createCurrentInjector (
@@ -205,4 +206,38 @@ function injectService(token: any, notFoundValue?: any) {
205
206
return currentInjector . get ( token , notFoundValue )
206
207
}
207
208
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