未捕获(承诺):错误:没有字符串

时间:2017-08-16 10:36:57

标签: angular dependency-injection

我是angular2的新手,我遇到了这个错误。 我有一个这样的课程

@Injectable()
export class VehicleDetails {
    constructor(private policynumber: string, private vinnumber: string) {
        this.policyNumber = policynumber,
            this.vinNumber = vinnumber
    }
    policyNumber: string;
    vinNumber: string;
}

和另一个类似的

export class Policy {
    constructor() {
    }
    emailAddress: string;
    vehicleDetails: VehicleDetails[]
}

我已经在像这样的模块中导入了我的课程

import { Policy } from './models/Policy';
import { VehicleDetails } from './models/VehicleDetails';
@NgModule({
  declarations: [
    LienholderComponent,
    AppComponent,
    PolicyVehicleComponent
  ],
  imports: [
    RouterModule.forRoot(
      APP_ROUTES,
      { enableTracing: true } // <-- debugging purposes only
    ),
    BrowserModule,
    FileUploadModule,
    ReactiveFormsModule,
    HttpModule
  ],
  providers: [Policy, VehicleDetails],
  bootstrap: [AppComponent]
})
export class AppModule { }

当我在VehicleDetails类中注释我的构造函数时,一切正常,但是当我使用构造函数时,我开始得到这个错误。 如何解决这个错误,我在构造函数中有两个字符串参数,因为我想动态添加值。

我的错误是这个

enter image description here

  

我想要实现像这样构建VehicleDetails类   是

this.policy.emailAddress='email@test.com';
    this.policy.vehicleDetails.push(new VehicleDetails('valueA1','valueA2'));
    this.policy.vehicleDetails.push(new VehicleDetails('valueB1','valueB2'));
    this.policy.vehicleDetails.push(new VehicleDetails('valueC1','valueC2'));

所以,我动态获取值,我想将值绑定到模型,如上面的代码所述

2 个答案:

答案 0 :(得分:6)

DI无法创建VehicleDetails的实例,因为它没有关于private policynumber: string, private vinnumber: string

传递内容的任何信息

您可以做的是使用@Inject()装饰器

constructor(@Inject('policy') private policynumber: string, @Inject('vin') private vinnumber: string) {

并提供类似

的值
providers: [Policy, VehicleDetails, {provide: 'policy', useValue: 'abc'}, {provide: 'vin', useValue: 'def'}],

答案 1 :(得分:1)

根据您的问题更新,您不需要@Injectable装饰器。将您的VehicleDetails更改为:

export class VehicleDetails {
    constructor(policynumber: string, vinnumber: string) {
        this.policyNumber = policynumber,
            this.vinNumber = vinnumber
    }
    policyNumber: string;
    vinNumber: string;
}

并从VehicleDetails提供商处删除AppModule