0
我想擴展ngx-translate的管道,使其在我的應用程序中具有潛在的多用途。如何擴展ngx-translate管道
我管:
import { Pipe, PipeTransform } from '@angular/core';
import { TranslatePipe } from "@ngx-translate/core";
@Pipe({
name: 'msg'
})
export class MsgPipe extends TranslatePipe implements PipeTransform {
transform(value: any, args: any[]): any {
return super.transform(value, args)
}
}
爲了等待有關轉換模塊加載,我用角的APP_INITIALIZER:
app.module:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { appRoutes } from './app.routes';
import { AppComponent } from './root/app.component';
import { PageNotFoundComponent } from './shared/components/page-not-found/page-not-found.component';
import { HomePageComponent } from './shared/components/home-page/home-page.component';
import { MsgPipe } from './shared/pipes/msg.pipe';
import { ChangeDetectorRef } from '@angular/core';
import { TranslateModule, TranslateLoader } from "@ngx-translate/core";
import { Injector, APP_INITIALIZER } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { LOCATION_INITIALIZED } from '@angular/common';
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
export function appInitializerFactory(translate: TranslateService, injector: Injector) {
return() => new Promise<any>((resolve: any) => {
const locationInitialized = injector.get(LOCATION_INITIALIZED, Promise.resolve(null));
locationInitialized.then(() => {
const langToSet = 'en'
translate.setDefaultLang('en');
translate.use(langToSet).subscribe(() => {
console.info(`Successfully initialized '${langToSet}' language.'`);
}, err => {
console.error(`Problem with '${langToSet}' language initialization.'`);
},() => {
resolve(null);
});
});
});
}
@NgModule({
declarations: [
AppComponent,
PageNotFoundComponent,
HomePageComponent,
MsgPipe
],
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes),
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
}),
],
providers: [
{
provide: APP_INITIALIZER,
useFactory: appInitializerFactory,
deps: [TranslateService, Injector],
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
(代碼以上取自here)
我的菸斗還沒有窩除非pure被設置爲false,否則會導致多次不必要的調用。沒有錯誤,它只是不會改變內容。
我明白你在做什麼,我只是想知道你爲什麼不使用ngx之類的東西,你自己寫這個的原因是什麼? –
因爲ngx是一個第三方庫,你說我想定製,因爲你不需要ngx,你只需要一個管道文件和提供者就可以做同樣的事情...... :) –
你如何處理插值安全的方式?該庫提供了選項來傳遞對象並替換字符串變量,您的解決方案是否解決了這個問題? –