我有一个 Angular 7 通用应用程序,有两种语言,西班牙语和英语。我想以用户配置的语言显示网站。为了实现这一点,我有以下设置。
首先我app.component.html
只有一个这样的路由器插座:
<router-outlet></router-outlet>
在我的app-routing.module.ts
我有以下配置:
{
path: 'es',
data: { lang: 'es' },
component: LanguageComponent,
children: [
{
path: '',
loadChildren: () => import('./home/home.module').then(m => m.HomeModule),
},
{
path: '**',
redirectTo: 'pagina-no-encontrada'
}
],
},
{
path: 'en',
data: { lang: 'en' },
component: LanguageComponent,
children: [
{
path: '',
loadChildren: () => import('./home/home.module').then(m => m.HomeModule),
},
{
path: '**',
redirectTo: 'page-not-found'
}
],
},
{
path: '',
component: LanguageComponent,
pathMatch: 'full'
},
{
path: '**',
redirectTo: '/es/pagina-no-encontrada',
pathMatch: 'full'
},
我这样做是为了让LanguageComponent
检测用户语言并重定向到相关的/es
或/en
.
我language.component.ts
的逻辑如下:
import { Component, OnInit, OnDestroy, Inject, PLATFORM_ID, Renderer2 } from '@angular/core';
import { ActivatedRoute, Data, Router } from '@angular/router';
import { TranslateService } from '../services/translate.service';
import { Subscription } from 'rxjs/internal/Subscription';
import { LANG_EN_NAME } from '../translate/lang-en';
import { LANG_ES_NAME } from '../translate/lang-es';
import { isPlatformBrowser, DOCUMENT } from '@angular/common';
@Component({
selector: 'app-language',
templateUrl: 'language.component.html',
styleUrls: ['language.component.scss']
})
export class LanguageComponent implements OnInit, OnDestroy {
private subscription: Subscription;
private isPlatformBrowser: boolean;
constructor(private activatedRoute: ActivatedRoute,
private translate: TranslateService,
private router: Router,
@Inject(PLATFORM_ID) private platformId: Object) {}
ngOnInit(): void {
this.isPlatformBrowser = isPlatformBrowser(this.platformId);
this.subscription = this.activatedRoute.data.subscribe((d: Data) => {
if (d['lang'] !== undefined) {
this.translate.use(d['lang']);
} else if (this.isPlatformBrowser && navigator) {
const userLanguage = navigator.language;
if (userLanguage) {
if (userLanguage.startsWith('en')) {
this.router.navigateByUrl(LANG_EN_NAME);
} else {
this.router.navigateByUrl(LANG_ES_NAME);
}
}
} else {
this.router.navigateByUrl(LANG_ES_NAME);
}
});
}
ngOnDestroy(): void {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}
所以我可以通过导航器成功检测语言并通过转到相关部分来显示页面。HomeComponent
在HomeModule中的每个组件上,我调用一个SeoService
设置标题、元描述并根据设置的语言设置 HTML 语言标签的组件。
我遇到的问题很奇怪,因为它涉及到谷歌搜索结果。有时我得到的网站的标题显示为西班牙语,然后是英文的描述,有时全是英文……所有的一切都开始发生,因为我决定开始使用导航器作为语言检测的驱动程序。
首先,我不知道在这种情况下我的方法是否是最好的,如果是,您是否遇到过谷歌引擎语言问题?
更新: 我认为我的问题更多的是为了执行 SSR,我需要了解用户浏览器的语言。是否有可能以某种方式将该值“传输”到服务器以执行该渲染?否则,我真的不知道如何知道“用户设置”来执行页面的实际呈现,并且如果这有意义的话是“谷歌友好的”