Skip to content

Commit

Permalink
fix(useFactory): allow use of $inject on factory methods
Browse files Browse the repository at this point in the history
Fixes #25
  • Loading branch information
Jason Bedard committed May 24, 2017
1 parent bec50ae commit 568ba58
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
52 changes: 52 additions & 0 deletions src/facade.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,58 @@ describe("facade", function() {
expect("$apply" in instance.a).toBe(true);
expect(instance.b).toEqual(jasmine.any(Foo));
});

it("should support factory.$inject to inject into factory method", function() {
@Injectable()
class Foo {}

class Bar {
constructor(public a, public b) {}
}

function factory(a, b) { return new Bar(a, b); }
(<any>factory).$inject = ["$rootScope", Foo];

@NgModule({
id: "test",
providers: [Foo, {
provide: Bar,
useFactory: factory
}]
})
class Mod {}

const instance = bootstrapAndInitialize("test", Bar);

expect(instance).toEqual(jasmine.any(Bar));
expect("$apply" in instance.a).toBe(true);
expect(instance.b).toEqual(jasmine.any(Foo));
});

it("should throw if both factory.$inject and deps declared", function() {
@Injectable()
class Foo {}

class Bar {
constructor(public a, public b) {}
}

function factory(a, b) { return new Bar(a, b); }
(<any>factory).$inject = ["$rootScope", Foo];

expect(function() {
@NgModule({
id: "test",
providers: [Foo, {
provide: Bar,
useFactory: factory,
deps: ["$rootScope", Foo]
}]
})
class Mod {}
})
.toThrow();
});
});

describe("useExisting", function() {
Expand Down
9 changes: 8 additions & 1 deletion src/facade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,14 @@ function setupProvider(mod: angular.IModule, provider: Provider): void {
}
//FactoryProvider
else if (isFactoryProvider(provider)) {
mod.factory(provider.provide, extend(provider.useFactory, {$inject: provider.deps || []}));
const factory = provider.useFactory;
if (provider.deps) {
if (factory.$inject) {
throw new Error("Can not declare both $inject and deps for a factory");
}
factory.$inject = provider.deps;
}
mod.factory(provider.provide, factory);
}
//ClassProvider
else if (isClassProvider(provider)) {
Expand Down

0 comments on commit 568ba58

Please sign in to comment.