Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No provider for Array

Tags:

angular

I just started with Angular RC6. I imported HttpModule inside my @NgModule decorator.

However I get this exception: No provider for Array!

How can I fix this?

-- edit--: For some reason this error is caused by:

constructor(private myService: CustomService, public items: Item[]) { }
like image 691
Depzor Avatar asked Sep 02 '16 09:09

Depzor


2 Answers

If a constructor of a service, component, or directive contains parameters, Angulars dependency injection tries to find a provider to get a value from it that it then passes to the constructor.

You don't have a provider registered for the type Item[].
Either

  • you register a provider
  • you add @Optional() before public items: Item[] so Angulars DI is allowed to ignore the parameter if it doesn't find a provider
  • you remove the parameter from the constructor.
like image 179
Günter Zöchbauer Avatar answered Nov 17 '22 17:11

Günter Zöchbauer


Just initialize the array outside the constructor and create it in the constructor i.e.

export class Animal{    

    public animals: Animal[]; //initializing outside the constructor

    constructor(private animal: Animal) {

        this.animals = new Array<Animal>(); //creating inside the constructor

        animals.push(animal); //adding element to the array
    }        
}
like image 3
WasiF Avatar answered Nov 17 '22 18:11

WasiF