2016-05-18 108 views
0

我的目標是使用定義組件的templateUrl屬性的常量值(基本URL)的依賴注入。迄今沒有任何工作。下面的代碼在Typescript中Angular 1.5組件 - 依賴注入

一些解釋:app.core.Iconstants包含baseUrl值。 app.core.AngularGlobals.appCoreConstants是表示「app.core.Constants」的字符串。

請注意,我只是削減了Angular的牙齒。

命名空間donationEntry.Components {0,使用嚴格的;

class test1 implements ng.IComponentOptions { 
    public static id: string = AngularGlobals.donationEntry + ".test1"; 
    bindings: any; 
    controller: any; 
    templateUrl: string; 

    constructor(clientContext: app.core.IConstants) { 
     this.bindings = { 
      textBinding: '@', 
      dataBinding: '<', 
      functionBinding: '&' 
     }; 
     this.controller = TestController; 
     this.templateUrl = clientContext.baseUrl + "Areas/ng/app/fundraising/donationEntry/components/test1/test1.html"; 
    } 
} 

// register the controller with app 
angular.module(AngularGlobals.donationEntry) 
    .component("test1", [app.core.AngularGlobals.appCoreConstants, (c) => new test1(c)]); 

}

當運行此,我結束了以下錯誤:

angular.js:61未被捕獲的錯誤:[$注射器:modulerr]未能實例模塊的應用程序由於: 錯誤:[$注射器:modulerr]未能實例化模塊donationEntry由於: 類型錯誤:t.charAt不是一個函數

+0

說你是一個對象不具有的charAt上調用的charAt,但我沒有看到任何地方的charAt在你提供的片段中,你確定這是問題所在嗎? –

+0

繞過這個問題,我從來沒有深入過,但它似乎與我使用的快捷方式注入語法有關。 –

回答

0

這似乎工作,雖然我不會把它最有說服力的答案。再次,在Typescript中編寫:

namespace donationEntry.Components {0} {0} {0}

class test1 implements ng.IComponentOptions { 
    public static id: string = AngularGlobals.donationEntry + ".test1"; 
    bindings: any; 
    controller: any; 
    templateUrl: string; 


    constructor(clientContext: app.core.IConstants) { 
     this.bindings = { 
      textBinding: '@', 
      dataBinding: '<', 
      functionBinding: '&' 
     }; 
     this.controller = TestController; 
     this.templateUrl = clientContext.baseUrl + "Areas/ng/app/fundraising/donationEntry/components/test1/test1.html"; 
    } 
} 

// register the controller with app 
var clientContext = <app.core.IConstants>angular.injector(['ng', app.core.AngularGlobals.appCore]).get(app.core.AngularGlobals.appCoreConstants); 
angular.module(AngularGlobals.donationEntry) 
    .component("test1", new test1(clientContext)); 

}

0

我儘量遠離角的注射或模塊機制時,我可以離開,寧願直ES6。

你可以這樣做:

//clientContext.ts 
export = { baseUrl: 'whateva' } 

,然後導入這樣的:

import clientContext from './path/to/clientContext' 
+0

謝謝。這很好,但是即使客戶端上下文路徑本身也需要動態基礎文本(我們的客戶端會有與我們不同的)。當然瞭解你不喜歡注射,嘿。 –