Royi Namir
Royi Namir

Reputation: 148624

What is the right way to use `useFactory` and `deps:[ ]` in Angular?

I want to use a simple provider with useFactory which will also use deps (learning purpose) .

So I've created this plnkr :

//app.module.ts
...
const randomFactory = (car,engine) => { return new Calc(car,engine);  };
 ...
 providers: [Car,Engine, 
             { provide: 'Random', 
               useFactory: randomFactory ,  
               deps: [Car, Engine],
             },
            ]

Where Calc is :

export class Calc
{
  car:Car;
  engine:Engine;

  constructor ( Engine engine, Car car)
   {
    this.car=car;
    this.engine=engine;
   }
  doSomething(){alert(this.car.getInfo() + this.engine.getInfo()}
}

Now I want to use it as an injected object so I did this :

export class AppComponent {
  constructor(@Inject('Random') r) {
    r.doSomething(); //should alert "car data + engine data" , but I get an error.
   }
}

But I get an error : car is not defined

Question:

I don't see any point of using deps:[] If I already declare that modules in the main app module ( and so it is known in the global app) and in the Calc class where I import those classes.

So how can I fix my code to use deps:[] the right way ?

plnkr

Upvotes: 3

Views: 1995

Answers (1)

George K
George K

Reputation: 1763

The providers configuration is correct. You've got a syntax error in the Calc constructor. The correct declaration of the arguments is as follows:

constructor (engine: Engine, car: Car){

Here is the updated plunker:

https://plnkr.co/edit/HsECR0HEcIaPNbK6A7ZZ?p=preview

Upvotes: 2

Related Questions