2017-03-09 132 views
0

我相對比較新,所以我想實現依賴注入使用typescript(是我第一次使用這種模式),我更多的是使用語言編程像java或c#OOP,所以更容易應用這種模式, 我在互聯網上找到一個例子,我可以在eclipse和visual studio上使用它,但是當我在打字稿上使用它時,IDE會報錯像這樣:有沒有辦法使用依賴關係注入使用typescript

Supplied parameters do not match any signature of call target 

,是剛剛在這個時候出現錯誤

實現它的結束

我的基類:

class Motor { 
    Acelerar(): void { 
    } 
    GetRevoluciones(): number { 
     let currentRPM: number = 0; 
     return currentRPM; 
    } 
} 
export {Motor}; 

我的類,它通過電機

import { Motor } from "./1"; 
class Vehiculo { 
    private m: Motor; 
    public Vehiculo(motorVehiculo: Motor) { 
     this.m = motorVehiculo; 
    } 
    public GetRevolucionesMotor(): number { 
     if (this.m != null) { 
      return this.m.GetRevoluciones(); 
     } 
     else { 
      return -1; 
     } 
    } 
} 
export { Vehiculo }; 

我的接口和電機

interface IMotor { 
    Acelerar(): void; 
    GetRevoluciones(): number; 
} 
class MotorGasoline implements IMotor { 
    private DoAdmission() { } 
    private DoCompression() { } 
    private DoExplosion() { } 
    private DoEscape() { } 
    Acelerar() { 
     this.DoAdmission(); 
     this.DoCompression(); 
     this.DoExplosion(); 
     this.DoEscape(); 
    } 
    GetRevoluciones() { 
     let currentRPM: number = 0; 
     return currentRPM; 
    } 
} 
class MotorDiesel implements IMotor { 
    Acelerar() { 
     this.DoAdmission(); 
     this.DoCompression(); 
     this.DoCombustion(); 
     this.DoEscape(); 
    } 
    GetRevoluciones() { 
     let currentRPM: number = 0; 
     return currentRPM; 
    } 
    DoAdmission() { } 
    DoCompression() { } 
    DoCombustion() { } 
    DoEscape() { } 
} 

的類型,這裏是出現在錯誤:

import { Vehiculo } from "./2"; 
enum TypeMotor { 
    MOTOR_GASOLINE = 0, 
    MOTOR_DIESEL = 1 
} 
class VehiculoFactory { 
    public static VehiculoCreate(tipo: TypeMotor) { 
     let v: Vehiculo = null; 
     switch (tipo) { 
      case TypeMotor.MOTOR_DIESEL: 
       v = new Vehiculo(new MotorDiesel()); break; 
      case TypeMotor.MOTOR_GASOLINE: 
       v = new Vehiculo(new MotorGasoline()); break; 
      default: break; 
     } 
     return v; 
    } 
} 

我不想使用任何庫或模塊喜歡簡單,DIJS或D4js或任何其他的那一刻,我只是想知道如何沒有他們實現

回答

0

你有這樣的錯誤,因爲你不指定在Vehiculo類型上的構造函數。

要聲明構造函數,您應該使用constructor關鍵字而不是類的名稱。

class Vehiculo { 
    private m: Motor; 
    constructor(motorVehiculo: Motor) { 
     this.m = motorVehiculo; 
    } 
    public GetRevolucionesMotor(): number { 
     if (this.m != null) { 
      return this.m.GetRevoluciones(); 
     } 
     else { 
      return -1; 
     } 
    } 
} 
+0

的作品,謝謝你,但你有一個想法,如何把參數代入類工廠假設不是「車用汽油」和「電動汽車」有它自己的構造 – Lrawls

+0

我不明白這一點。你能用代碼示例更新你的問題嗎?你想做什麼? –

+0

忘了它,它完成了 – Lrawls

相關問題