Angular多级依赖注入

时间:2018-09-09 13:52:32

标签: angular dependency-injection dependencies constructor-injection

我正试图了解Angular框架依赖注入的解决方案。

我有一个名为 Car 的服务,该服务具有一个 fetchCarDetails(cylinderQuant,tyretype)功能,具体取决于 Engine (马力)和 轮胎 (品牌)类。

然后在 User-demo 组件中手动解析Car类,并在其中提供Engine和Tire类的参数。

1)汽车等级

import { Injectable, ReflectiveInjector } from '@angular/core';
import { EngineService } from '../services/engine.service';
import { TyreService } from '../services/tyre.service';

@Injectable()
export class CarService {
constructor(public engine: EngineService, public tyre: TyreService) { }

fetchCarDetails(cylinderQuant, tyretype) {
this.engine.cylinders = cylinderQuant;
this.tyre.tyrebrand = tyretype;
return `car has ` + `${this.engine.cylinders} and ${this.tyre.tyrebrand} as a whole.`;
}

2)引擎

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

@Injectable()
export class EngineService {
 cylinders;
 constructor(cylindernum) {
  this.cylinders = cylindernum;
}
 }
}

3)轮胎

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

@Injectable()
export class TyreService {
tyrebrand: any;
constructor(tyre) {
this.tyrebrand = tyre;
 }
}

4)用户演示

import { Component, ReflectiveInjector } from '@angular/core';
import { CarService } from '../services/car.service';
import { EngineService } from '../services/engine.service';
import { TyreService } from '../services/tyre.service';

@Component({
  selector: 'app-user-demo',
  templateUrl: './user-demo.component.html',
  styleUrls: ['./user-demo.component.css']
})
export class UserDemoComponent {

  carService: CarService;
  EngineService: CarService;
  TyreService: CarService;
  carDemo: string;
  constructor() {

  const injector: any = ReflectiveInjector.resolveAndCreate([CarService, EngineService, TyreService]);
    this.carDemo = injector.get(CarService);
  }

  CarDetails(): void {

    this.carDemo = this.carService.fetchCarDetails(12, 'ceat');

    console.log('Details are : ', this.carDemo);
  }   
 }
}

在运行时出现以下错误。欢迎此处的任何帮助/建议。

错误:无法解析'EngineService'(?)的所有参数。确保所有参数都用Inject修饰或具有有效的类型注释,并且'EngineService'用Injectable修饰。 错误:无法解析“ EngineService”(?)的所有参数。确保所有参数都用Inject修饰或具有有效的类型注释,并且'EngineService'用Injectable修饰。

Exception

0 个答案:

没有答案