2014-07-27 29 views
0

我想了解如何將服務帶入控制器中,當該服務在父控制器和子控制器中使用時父母和孩子的HTML。我應該把服務到父,然後讓該服務的副本從範圍在孩子這樣的:當一個服務注入父控制器時,我應該也注入到孩子或只是繼承服務

class AppController { 
    static $inject = [ 
     '$scope', 
     'configService' 
    ] 
    constructor(
     public $scope: IAppControllerScope, 
     public config: IConfigService 
     ) { 
     $scope.app = this; 
     $scope.config = config; 
    } 
    // this.config is used here 
} 
class AdminHomeController { 
    public app: AppController; 
    public config: ConfigService; 
    static $inject = [ 
     '$scope' 
    ]; 
    constructor(
     private $scope: IAdminHomeControllerScope 
     ) { 
     this.app = $scope.app; 
     this.config = $scope.config; 
     $scope.home = this; 
    } 
    // this.config is used here 
} 

或者我應該把服務爲雙方父母和孩子的控制器是這樣的:

class AppController { 
    static $inject = [ 
     '$scope', 
     'configService' 
    ] 
    constructor(
     public $scope: IAppControllerScope, 
     public config: IConfigService 
     ) { 
     $scope.app = this; 
     $scope.config = config; 
    } 
    // this.config is used here 
} 
class AdminHomeController { 
    public app: AppController; 
    static $inject = [ 
     '$scope', 
     'configService' 
    ]; 
    constructor(
     public $scope: IAdminHomeControllerScope, 
     public config: IConfigService 
     ) { 
     this.app = $scope.app; 
     $scope.home = this; 
    } 
    // this.config is used here 
} 

我將不勝感激任何意見和建議,哪些是最好的方式來做到這一點,如果有差異。還有一個問題。我的構造函數的參數應該被聲明爲私有還是公共?

回答

2

這是你的選擇,但是你更喜歡這樣做,但是將它直接包含在每個控制器中的一個參數是,你對其他任何控件都沒有依賴關係。

AppController包括在內並且被繼承的問題在於,如果無論出於何種原因一個開發人員決定「我們不再在這裏揉揉它」,那麼您將擁有所有其他控制器認爲服務在那裏打破。 - @ basarat告訴我,TypeScript事實上只是無法編譯,但顯然還是比不存在問題更爲棘手。在這種情況下,你要麼必須把它放回去,要麼進入每個給出編譯錯誤的控制器並將它們注入到它們中,因此無論如何你最終都會回到第一個解決方案。

通過將其直接包含到每個控制器中,如果將其從其中一個控制器中刪除,則對其餘應用程序沒有影響。它只是讓事情更安全一些。

如果您真的只想包括一次並在任何地方使用它,您應該可以使用角run方法在應用程序運行時將其注入到rootScope中。你可以做如下的事情。

myApp.run(function($rootScope, myService) { 
    $rootScope.myService = myService; 
}) 
// For declaring that myService exists on all instances of $scope: 
module ng{ 
    export interface IScope{ 
     myService: MyService; 
    } 
} 
+0

它不會在打字稿中壞掉。 – basarat

+0

什麼不?我發佈的代碼或從應用程序控制器中刪除的服務? – PaReeOhNos

+1

如果更新基礎範圍以刪除服務,其餘控制器將無法編譯。所以用法參數在這裏是無效的。 – basarat