如果我正確理解,你想創建一個服務,可以作爲角的DI過程中的幫手。
就像@Günter_Zöchbauer說的,Injectable不能用在Ng2對象(Component,Injectable ...)實例的外部,但在你的情況下,創建一個注射是無關緊要的。 創建角度應用並不意味着所有的文件必須包含的角度對象,你還可以創建基本的類/常數..
例如,如果希望建立一個網址給你的幫手,可以創建一個類,並通過簡單地導入它來在組件聲明中使用它。
//urlbuilder.ts
const host:string = 'http://foo.bar.com';
export class UrlBuilder {
static generate(file:string = '') {
return host + file;
}
}
// component.ts
import {UrlBuilder} from './urlbuilder';
@Component({
templateUrl: UrlBuilder.generate('/foo.html')
})
export class FooComponent {}
你甚至可以導出一個函數而不是類,它也可以工作。 以下代碼顯示與上面相同的代碼,但帶有一個功能和一個es6標籤。
//urlbuilder.ts
const host:string = 'http://foo.bar.com';
export const UrlBuilder = urlBuilderFn;
//basic tag function that build a template string with potential variables
function urlBuilderFn(strs, ...raws) {
let builtStr = '', length = strs.length;
for(let i = 0; i < length; i++)
builtStr = strs[i] + (raws[i] !== undefined && raws[i] !== null ? raws[i] : '');
return host + builtStr;
}
// component.ts
import {UrlBuilder as url} from './urlbuilder';
@Component({
templateUrl: url`/foo.html`
})
export class FooComponent {}
但是,如果想使用你的助手與DI太(不管是什麼原因,需要角度DEPS ..)可以使注射劑類的靜態方法。
//urlbuilder.ts
const host:string = 'http://foo.bar.com';
@Injectable()
export class UrlBuilder {
constructor(private http:Http) {}
static generate(file:string = '') {
return host + file;
}
doSomething() {
return this.http.get(UrlBuilder.generate('/foo/bar'))
}
}
// component.ts
import {UrlBuilder} from './urlbuilder';
@Component({
templateUrl: UrlBuilder.generate('/foo.html')
})
export class FooComponent {
constructor(private builder:UrlBuilder) {}
ngOnInit() {
this.builder.doSomething()
}
}
在另一方面,如果你唯一的問題是與模板你爲什麼不直接寫他們作爲模板字符串或只是與你的任務管理器中導入它們(的WebPack ..)。一般來說,如果您沒有動態視圖,那麼必須從服務器生成它們,而不是使用http調用來檢索它們,並直接將它們加載到JavaScript文件中。
DI在裝修中使用。有可能是黑客,但我很確定他們不能用AoT做例子。 –
是的,我認爲它不應該這樣工作,但不能以某種方式從另一個文件中導入一個函數,我可以在@Component聲明中使用它?我只是不喜歡我現在正在做的是在10個不同的組件中複製代碼,所以我可以注入正確的路徑前綴。 – Methodician