SimCity
SimCity

Reputation: 549

Angular2 class constructor error: no provider for Number

I've started a project using the development kit found here: https://github.com/datatypevoid/ng2-mean-webpack. Everything seems to work perfectly fine, except when I create a new class with parameters properties (as seen on the official Typescript documentation here: https://www.typescriptlang.org/docs/handbook/classes.html), I get an error message in the console saying:

ORIGINAL EXCEPTION: No provider for Number!

Here is my class:

@Component({
  selector: 'grid-tile',
  template: require('./grid-tile.component.html'),
  styleUrls: [require('!style!css!sass!./grid-tile.component.scss')],
  providers: [],
  directives: [],
  pipes: []
})
export class GridTile extends Tile {
  constructor(private x:number, private y: number) {
    super();
  }
}

And a here is how I create the instances:

var tile = new GridTile(3,4);
tiles.push(tile);

I would really appreciate finding a solution for this problem as I go further into development. I've followed the Angular2 Tour of Heroes tutorial and parameter properties seemed to work fine, so I'm wondering if it has something to do with the development kit or simply something I'm passing on.. I'm totally new with Angular2, so this may be a mistake by my fault. Thanks for the help.

Upvotes: 4

Views: 10043

Answers (1)

robisim74
robisim74

Reputation: 776

Angular 2 uses MVC pattern: a class decorated with @Component is equivalent to a Controller. This means that:

  • you can not provide parameters to the constructor if you do not use Dependency Injection (this generates the error);

  • the class should not be instantiated, but must be invoked at the time of the bootstrap, or through a router, or in Angular passing it as a child through a directive.

If you carefully analyze the Tour of Heroes, you will notice that you create a service, that is an injectable class:

@Injectable()
export class HeroService {
  ...
  }
}

Then you inject it as a provider (in the same component or in a parent), and instantiate by passing it to the constructor of the component:

@Component({
  selector: 'my-app',
  ...
  providers: [HeroService]
})
export class AppComponent implements OnInit {
  ...
  constructor(private heroService: HeroService) { }
  ...
}

In this way the reference to the injected class is inherited by the component and by all child components.

In your example, you have two variables as parameters, and the error is generated because they don't correspond to any provider in the component.

You can read more here.

Or, to begin: http://victorsavkin.com/post/118372404541/the-core-concepts-of-angular-2

Upvotes: 6

Related Questions