Skip to content

Commit edf85eb

Browse files
committed
fix: correct provides handling in provideService function
1 parent ed354bf commit edf85eb

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

src/di/index.ts

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -170,18 +170,31 @@ interface Constructable {
170170
constructor: Function
171171
}
172172
function provideService<T extends Constructable>(...service: T[]) {
173-
const instance = getCurrentInstance()!
173+
const currentInstance = getCurrentInstance()!
174+
// @ts-ignore
175+
let provides = currentInstance.provides
176+
// by default an instance inherits its parent's provides object
177+
// but when it needs to provide values of its own, it creates its
178+
// own provides object using parent provides object as prototype.
179+
// this way in `inject` we can simply look up injections from direct
180+
// parent and let the prototype chain do the work.
181+
// @ts-ignore
182+
const parentProvides = currentInstance.parent && currentInstance.parent.provides
183+
if (parentProvides === provides) {
184+
// @ts-ignore
185+
provides = currentInstance.provides = Object.create(parentProvides)
186+
}
174187
// @ts-ignore
175188
let injector: ReflectiveInjector
176-
if (Reflect.has(instance, InjectorKey as symbol)) {
189+
if (Object.prototype.hasOwnProperty.call(provides, InjectorKey as symbol)) {
177190
// @ts-ignore
178-
injector = instance.provides[InjectorKey]
191+
injector = currentInstance.provides[InjectorKey]
179192
}
180193
// @ts-ignore
181194
if (!injector) {
182195
injector = ReflectiveInjector.resolveAndCreate([], inject(InjectorKey))
183196
// @ts-ignore
184-
instance.provides[InjectorKey] = injector
197+
currentInstance.provides[InjectorKey] = injector
185198
}
186199

187200
ReflectiveInjector.resolve(service.map(k => ({ provide: k.constructor, useValue: k }))).forEach((provider, i) => {

0 commit comments

Comments
 (0)