2017-08-09 56 views
1

我有一個簡單component這樣的:錯誤,同時還與參數的構造函數組件

@Component({ 
    selector: 'error-handler', 
    templateUrl: './error-handler.component.html', 
    styleUrls: ['./error-handler.component.css'] 
}) 
export class ErrorHandlerComponent { 

    constructor(public error?: any) { } 
} 

,當我去到瀏覽器我得到一個錯誤:

Uncaught Error: Can't resolve all parameters for ErrorHandlerComponent: (?). 

我必須註冊在我的新component模塊,所以我不知道爲什麼這個錯誤發生。我不會從任何地方調用構造函數。

+0

刪除'公共誤差不工作? :任何'從你的構造函數,並把它作爲一個變量放在類中。 – Faisal

+0

@Faisal沒有幫助 – Aryjadna

+1

那麼我們需要更多關於您的代碼的信息 – Faisal

回答

0

組件(或指令,或管道或服務)中的構造函數參數將嘗試由依賴注入器注入。您的成分改成這樣:

@Component({ 
    //... 
}) 
export class ErrorHandlerComponent { 

    public error: any 

    constructor() {} 
} 

或者使用 @Optional()裝飾:

@Component({ 
    //... 
}) 
export class ErrorHandlerComponent { 

    public error: any 

    constructor(@Optional()public error?: any) {} 
} 

可選當你的類型是any

+0

我有同樣的問題,並在您的更改後,我仍然有相同的錯誤 – bielas

+0

沒有幫助... – Aryjadna

+1

@Aryjadna根據您的代碼,這些是唯一的解決方案。如果第一個是更好的,因爲你永遠無法注入像這樣的任何一個。我的建議是,你可以看看https://angular.io提供的指南。或者確保我所建議的更改在您的項目中得到了真正的處理 – PierreDuc