Andrew
Andrew

Reputation: 169

Provide new instances of model class for dependency injection in Angular 2

I have a class that serves as a model for some data I get from a server. This data starts as an unwieldy xml object where text nodes have attributes so the json format I convert it into does not have simple string values. Instead I have:

@Injectable()
export class FooString {
  _attr: string;
  value: string;
  isReadOnly(): boolean {
    return this._attr && this._attr === 'ReadOnly';
  }

  isHidden(): boolean {
    return this._attr && this._attr === 'Hid';
  }
}

Then my model is like:

@Injectable()
export class Payment {
  constructor(
    public FooId: FooString,
    public FooStat: FooString,
    public FooName: FooString ) { }
}

Everything ends up with the same instance of FooString. How do I get discrete instances for each of them?

I have tried a factory, but it still only creates a single instance:

export let fooStringProvider = provide(FooString, {
  useFactory: (): FooString => {
    console.log('in foostring factory');
    return new FooString();
  }
});

Upvotes: 1

Views: 4603

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658067

new FooString();
new Payment();

;-)

Why using DI when they don't have dependencies and you don't want to maintain single instances per provider. Therefore, just use new.

When to use DI

There are a few criterias when using DI instead of new the right thing:

  • If you want Angular to maintain and share instances
  • If you want to work with an interface or base class but then you want to configure from the outside what implementation should actually be used at runtime - like the MockBackend for Http during testing.
  • If you class has dependencies to instances and/or values provided by DI
  • If you want to be able to easily test classes in isolation (https://en.wikipedia.org/wiki/Inversion_of_control)
  • probably others ...

If there are good arguments to use DI, but you also want new instances then you can just provide a factory.

This answer https://stackoverflow.com/a/36046754/217408 contains a concrete example how to do that.

Using DI is usually a good idea. There are IMHO no strong arguments against using DI. Only when none of the above arguments apply and providing factories is too cumbersome, use new Xxx() instead.

Upvotes: 3

Related Questions