Angular 17: SSR与i18n并行
创始人
2024-10-15 12:30:37
0

解决方法如下所示:

  1. 首先,确保你已经安装了最新版本的Angular CLI。你可以使用以下命令来检查你的版本:
ng version
  1. 创建一个新的Angular项目:
ng new angular-ssr-i18n
  1. 进入项目目录:
cd angular-ssr-i18n
  1. 添加Angular Universal支持:
ng add @nguniversal/express-engine
  1. 创建一个新的Angular服务来处理i18n:
ng generate service i18n
  1. 在i18n.service.ts文件中添加以下代码:
import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Injectable({
  providedIn: 'root'
})
export class I18nService {
  constructor(private translate: TranslateService) { }

  init() {
    this.translate.addLangs(['en', 'fr']);
    this.translate.setDefaultLang('en');
    const browserLang = this.translate.getBrowserLang();
    this.translate.use(browserLang.match(/en|fr/) ? browserLang : 'en');
  }
}
  1. 安装ngx-translate库:
npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader --save
  1. 在app.module.ts文件中添加以下代码:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http);
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'serverApp' }),
    HttpClientModule,
    AppRoutingModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
  1. 在app.component.html文件中添加以下代码:

{{ 'HELLO' | translate }}

  1. 在app.component.ts文件中添加以下代码:
import { Component, OnInit } from '@angular/core';
import { I18nService } from './i18n.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(private i18nService: I18nService, private translate: TranslateService) { }

  ngOnInit() {
    this.i18nService.init();
    this.translate.onLangChange.subscribe(() => {
      document.documentElement.lang = this.translate.currentLang;
    });
  }
}
  1. 在src/locales目录下创建en.json和fr.json文件,并添加以下内容:

en.json:

{
  "HELLO": "Hello World!"
}

fr.json:

{
  "HELLO": "Bonjour le monde!"
}
  1. 在server.ts文件中添加以下代码:
import 'zone.js/dist/zone-node';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';
import { existsSync } from 'fs';

const app = express();

const DIST_FOLDER = join(process.cwd(), 'dist/angular-ssr-i18n/browser');

const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/angular-ssr-i18n/server/main');

const { provideModuleMap } = require('@nguniversal/module-map-ngfactory-loader');

app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [provideModuleMap(LAZY_MODULE_MAP)]
}));

app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));

app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));

app.get('*', (req, res) => {
  const supportedLocales = ['en', 'fr'];
  const defaultLocale = 'en';
  const matches = req.url.match(/^\/([a-z]{2}(?:-[A-Z]{2})?)\//);
  const locale = (matches && supportedLocales.indexOf(matches[1]) !== -1

相关内容

热门资讯

透视开挂!hhpoker到底可... 透视开挂!hhpoker到底可以透视吗(透视)智星菠萝透视,教程项目(揭秘有挂)-哔哩哔哩1、完成h...
透视解密!wejoker辅助软... 透视解密!wejoker辅助软件视频(透视)pokernow辅助控制,教程诀窍(有挂讲解)-哔哩哔哩...
透视辅助!wepoker有没有... 透视辅助!wepoker有没有透视方法(透视)拱趴大菠萝万能挂,教程要领(有挂秘诀)-哔哩哔哩1、让...
透视分享!wepoker透视脚... 透视分享!wepoker透视脚本免费使用视频(透视)智星德州插件,教程妙计(有挂讲解)-哔哩哔哩在进...
透视普及!wepoker有辅助... 透视普及!wepoker有辅助功能吗(透视)wpk德州局透视,教程窍要(有挂助手)-哔哩哔哩1、we...
透视推荐!云扑克有透视吗(透视... 透视推荐!云扑克有透视吗(透视)wepokerplus万能挂,教程诀窍(有挂规律)-哔哩哔哩1、该软...
透视解谜!拱趴大菠萝机器人(透... 透视解谜!拱趴大菠萝机器人(透视)wpk辅助是什么,教程法门(有挂秘诀)-哔哩哔哩1、游戏颠覆性的策...
透视详细!aa poker透视... 透视详细!aa poker透视软件(透视)红龙poker辅助,教程大纲(有挂存在)-哔哩哔哩1、aa...
透视科普!wepoker透视视... 透视科普!wepoker透视视频(透视)wepoker透视脚本免费下载,教程机巧(有挂方略)-哔哩哔...
透视曝光!wepoker辅助器... 透视曝光!wepoker辅助器如何使用(透视)wepoker透视器免费,教程手段(有挂技巧)-哔哩哔...