Wayne
Wayne

Reputation: 71

Dependency injection constructor with parameters: Component in `RouteConfig` initial error

I have the app.component.ts like this:

import { RouteConfig, Router } from '@angular/router-deprecated';
@RouteConfig([
  {
    path: '/meter', name: 'Meter', component: Meter
  }
])

and app.tpl.html like this:

<main>
  <router-outlet></router-outlet>
</main>

The Meter component is like this:

import { Device } from './device.model';

@Component({
  selector: 'meter',
  providers: [Device],
  template: require('./meter.tpl.html')
})
export class Meter {
  constructor(
    public devices: Device
  ) {

  }
}

The Device model is like this:

import { Injectable } from '@angular/core';

@Injectable()
export class Device {    
  constructor(
    public deviceSerialNr: string
  ) {
      console.log('Device created');
  }
}

When I run the app, I get the error:

EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in :0:0
ORIGINAL EXCEPTION: No provider for String!
ORIGINAL STACKTRACE:
Error: DI Exception

But if I move the attribute public xx: XXX from constructor parameter to class root, it will be ok.

---------------UPDATE--------------

I should not inject Device class as a parameter in the angular component constructor. Just remove @Injectable from Device class and remove public device decalre from constructor of Meter.

Upvotes: 1

Views: 326

Answers (1)

micronyks
micronyks

Reputation: 55443

Problem is here,

@Injectable()
export class Device {    
  constructor(
    public deviceSerialNr: string  <------problem area
  ) {
      console.log('Device created');
  }
}

instead you should write,

@Injectable()
    export class Device {   
     public deviceSerialNr: string;   <------look here
      constructor() {
          console.log('Device created');
      }
  }

OR

@Injectable()
    export class Device {     
      constructor() {
          this.deviceSerialNr="someValue";     <------look here
          console.log('Device created');
      }
}

Upvotes: 1

Related Questions