带参数的依赖注入构造函数:`RouteConfig`初始错误中的组件

时间:2016-06-08 01:49:31

标签: angularjs angular

我有app.component.ts这样:

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

app.tpl.html是这样的:

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

Meter组件是这样的:

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

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

  }
}

Device模型是这样的:

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

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

当我运行应用程序时,我收到错误:

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

但是,如果我将属性public xx: XXXconstructor参数移动到类根,那就没问题了。

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

我不应该将Device类作为参数添加到角度组件构造函数中。只需从Device类中删除@Injectable,然后从Meter的构造函数中删除公共设备decalre。

1 个答案:

答案 0 :(得分:1)

问题在这里,

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

相反你应该写,

@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');
      }
}