首页 > 解决方案 > 如何以角度翻译 app.routing.module.ts 中的单词

问题描述

我有角度路由模块,我想在这个路由模块中从 ngx-translate 语言中获取一些单词,但我做不到,我尝试了这段代码,但它不起作用:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from '../../auth/auth.guard';
import { CategoryComponent } from './category/category.component';
import { SubCategoryComponent } from './category/sub-category/sub-category.component';

import { ColorsComponent } from './colors.component';
import { TypographyComponent } from './typography.component';

const routes: Routes = [
  {
    path: '',
    data: {
      title: "{{'NameEng' | translate}}"
    },
    children: [
      {
        path: '',
        redirectTo: 'colors'
      },
      {
        path: 'colors',
        component: ColorsComponent,
        data: {
          title: 'Colors'
        }
      },
      {
        path: 'typography',
        component: TypographyComponent,
        canActivate:[AuthGuard],
        data: {
          title: 'Typography'
        }
      },
      {
        path: 'category',
        component: CategoryComponent,
        canActivate:[AuthGuard],
        data: {
          title: 'Categories'
        }
      },
      {
        path: 'subcategory',
        component: SubCategoryComponent,
        canActivate:[AuthGuard],
        data: {
          title: 'Sub Categories'
        }
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class ThemeRoutingModule {}

我想从 translateService 获取标题数据,但它不起作用,你能帮我吗朋友谢谢

标签: angulartypescript

解决方案


据我所知,我想你正在使用CoreUI

CoreUI 实际上并不支持面包屑翻译,但您可以克隆面包屑组件并对其进行修改以使其可翻译。

此答案是此处提供的答案的修改版本。

breadcrumb.component.html(请注意,它会尝试获取翻译后的标题,如果不存在,它将显示您在title键中使用的原始值。

<ol class="breadcrumb">
<ng-container *ngFor="let breadcrumb of breadcrumbs | async, let last = last">
    <li class="breadcrumb-item"
        *ngIf="breadcrumb.label.title && (breadcrumb.url.slice(-1) == '/' || last)"
        [ngClass]="{active: last}">
        <a *ngIf="!last" [routerLink]="breadcrumb.url" >{{ tr[breadcrumb.label.title] != null ? tr[breadcrumb.label.title] : breadcrumb.label.title }}</a>
        <span *ngIf="last" [routerLink]="breadcrumb.url" >{{ tr[breadcrumb.label.title] != null ? tr[breadcrumb.label.title] : breadcrumb.label.title }}</span>
    </li>
</ng-container>

面包屑.component.ts

import {Component, ElementRef, Inject, Input, OnDestroy, OnInit, Renderer2} from '@angular/core';
import {DOCUMENT} from '@angular/common';
import {TranslationService} from '../../../services/translation.service';


import {BreadcrumbService} from './breadcrumb.service';

function Replace(el: any): any {
    const nativeElement: HTMLElement = el.nativeElement;
    const parentElement: HTMLElement = nativeElement.parentElement;

    // move all children out of the element
    while (nativeElement.firstChild) {
        parentElement.insertBefore(nativeElement.firstChild, nativeElement);
    }

    // remove the empty element(the host)
    parentElement.removeChild(nativeElement);
}

@Component({
    selector: 'app-custom-breadcrumb',
    templateUrl: './breadcrumb.component.html',
})
export class BreadcrumbComponent implements OnInit, OnDestroy {
    public tr; // servicio de traduccion


    @Input() fixed: boolean;
    breadcrumbs;
    private readonly fixedClass = 'breadcrumb-fixed';

    constructor(
        @Inject(DOCUMENT) private document: any,
        private renderer: Renderer2,
        public service: BreadcrumbService,
        public el: ElementRef,
        private translationService: TranslationService,
    ) {
        this.tr = translationService.getTranslations();
    }

    ngOnInit(): void {
        Replace(this.el);
        this.isFixed(this.fixed);
        this.breadcrumbs = this.service.breadcrumbs;
    }

    ngOnDestroy(): void {
        this.renderer.removeClass(this.document.body, this.fixedClass);
    }

    isFixed(fixed: boolean = this.fixed): void {
        if (fixed) {
            this.renderer.addClass(this.document.body, this.fixedClass);
        }
    }
}

面包屑.service.ts(不变)

import { Injectable } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { BehaviorSubject, Observable } from 'rxjs';
import { filter } from 'rxjs/operators';

@Injectable({
    providedIn: 'root'
})
export class BreadcrumbService {

    breadcrumbs: Observable<Array<any>>;

    private breadcrumbSubject: BehaviorSubject<Array<any>>;

    constructor(private router: Router, private route: ActivatedRoute) {

        this.breadcrumbSubject = new BehaviorSubject<any[]>(new Array<any>());

        this.breadcrumbs = this.breadcrumbSubject.asObservable();

        this.router.events.pipe(filter(event => event instanceof NavigationEnd)).subscribe((event) => {
            const breadcrumbs = [];
            let currentRoute = this.route.root;
            let url = '';
            do {
                const childrenRoutes = currentRoute.children;
                currentRoute = null;
                // tslint:disable-next-line:no-shadowed-variable
                childrenRoutes.forEach(route => {
                    if (route.outlet === 'primary') {
                        const routeSnapshot = route.snapshot;
                        url += '/' + routeSnapshot.url.map(segment => segment.path).join('/');
                        breadcrumbs.push({
                            label: route.snapshot.data,
                            url
                        });
                        currentRoute = route;
                    }
                });
            } while (currentRoute);

            this.breadcrumbSubject.next(Object.assign([], breadcrumbs));

            return breadcrumbs;
        });
    }
}

现在,您的翻译服务应该如下所示:translation.service.ts

import {Injectable, LOCALE_ID, Inject} from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})


export class TranslationService {

    private trans_es;
    private trans_en;


    private localeId = '';
    private es = 'es';
    private en = 'en';


    public translatedLabels;

    headers: HttpHeaders = new HttpHeaders({
        'Content-Type': 'application/json'
    });

    constructor(@Inject(LOCALE_ID) private locale) {


        this.trans_es = {};
        this.trans_en = {};

        
        this.trans_es['typography'] = 'Tipografía';
        this.trans_en['typography'] = 'Typography';
        this.trans_es['colors'] = 'Colores';
        this.trans_en['colors'] = 'Colors';
       


        if (locale === 'en') {
            const s = JSON.stringify(this.trans_en);
            const c = JSON.parse(s);
            this.translatedLabels = c;
        } else {
            const s = JSON.stringify(this.trans_es);
            const c = JSON.parse(s);
            this.translatedLabels = c;
        }
    }

    public getTranslations() {
        return this.translatedLabels;
    }


}

然后在显示面包屑的 html 上:

<app-custom-breadcrumb>
        <li class="breadcrumb-menu d-md-down-none">
        </li>
</app-custom-breadcrumb>

最后你可以像这样在每条路线上使用它:

const routes: Routes = [
  {
    path: '',
    component: ColorsComponent,
    data: {
      title: 'colors'
    }
  }
];

推荐阅读