如何在NgModule定义文件中注入函数中的Location?

时间:2017-09-21 15:23:56

标签: angular typescript dependency-injection location

我有下一个代码

@NgModule({
    imports: [
     ..

    TranslateModule.forRoot({
        loader: {
            provide: TranslateLoader,
            useFactory: (createTranslateLoader),
            deps: [HttpClient]
        }
        }),
 ...

    ],

这是createTranslateLoader实现

export function createTranslateLoader(http: HttpClient) {
    let fullLocationPath = location.origin + location.pathname;
     // I want to use angular location here.
    return new TranslateHttpLoader(http, fullLocationPath  + 'assets/languages/', '.json');
}

我该怎么做?如何在createTranslateLoader函数中使用角度位置? https://angular.io/api/common/Location

1 个答案:

答案 0 :(得分:1)

根据documentation,您必须自己提供位置,如果您想使用它并指定LocationStrategy

import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';

@NgModule({
    imports: [
    ...
    TranslateModule.forRoot({
        loader: {
            provide: TranslateLoader,
            useFactory: createTranslateLoader,
            deps: [HttpClient]
        }
        }),
        ...

    ],

    providers: [Location, {provide: LocationStrategy, useClass: PathLocationStrategy}],

您可以通过3种位置策略中的任何一种:

  • HashLocationStrategy
  • PathLocationStrategy
  • MockLocationStrategy