1

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();
  }
});
Andrew
  • 138
  • 5
  • 14

1 Answers1

3
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.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thanks. I will do that. I don't understand when I should be using `new` and when I should be using Angular's DI. Can you enlighten me, or point me in the right direction? The example I gave above is one of the simple objects, but I have others that contain multiple complex data structures. The kind where it starts to look a lot like the Angular.io example of a car with an engine, tires, etc. On the surface it seems like DI would be great for this, but I can only have one instance? – Andrew May 04 '16 at 12:19