第一步 创建一个angular演示项目

安装angular cli

npm install -g @angular/cli

创建一个演示项目

ng new my-app

启动项目,访问localhost:4200出现下图就成功启动了

ng server


第二步 将ng-translate引入到my-app项目中

参见https://github.com/ngx-translate/core

npm install @ngx-translate/core @ngx-translate/http-loader rxjs --save

@ngx-translate/core 包含Translate的核心代码:TranslateService 和一些管道。

@ngx-translate/http-loader 从网络服务器加载翻译文件。

下载成功后将TranslateModule加入到my-app项目中的app.module.ts文件中

import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { HttpClient, HttpClientModule} from '@angular/common/http';
import { TranslateHttpLoader } from '@ngx-translate/http-loader/lib/http-loader';

export function createTranslateLoader(http: HttpClient): TranslateHttpLoader {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [HttpClient]
      },
      defaultLanguage: 'zh'
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

为应用程序初始化 TranslateService:

import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'my-app';
  constructor(translate: TranslateService) {
    // this language will be used as a fallback when a translation isn't found in the current language
    translate.setDefaultLang('zh');
     // the lang to use, if the lang isn't available, it will use the current loader to get them
    translate.use('zh');
}
}

第三步 使用国际化
导入 TranslateModule 后,可以将翻译放在一个 json 文件中,该文件将与 TranslateHttpLoader 一起导入。之后就可以通过pipe、service、Directive方式使用国际化了
pipe

 <span>{{ 'HOME.HELLO' | translate:'world' }}</span>

service

translate.get('HELLO', {value: 'world'}).subscribe((res: string) => {
    console.log(res);
    //=> 'hello world'
});

directive

<div [translate]="'HELLO'" [translateParams]="{value: 'world'}"></div>

(* ̄(oo) ̄)遇到报错:
原因报错里也给的很明白了版本问题,删掉重装即可

 ERROR in node_modules/@ngx-translate/core/public_api.d.ts:20:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.
    
    This likely means that the library (@ngx-translate/core) which declares TranslateModule has not been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.
    
    20 export declare class TranslateModule {
                            ~~~~~~~~~~~~~~~

解决方法:
顺序执行下面的两条命令即可

rm -rf node_modules
npm install
Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐