簡體   English   中英

如何在 angular 中翻譯 app.routing.module.ts 中的單詞

[英]how to translate words in app.routing.module.ts in angular

我有 angular 路由模塊,我想在這個路由模塊中從 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 獲取 Title 數據但是它不起作用你能幫助我嗎朋友謝謝

據我所知,我假設您正在使用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);
        }
    }
}

breadcrumb.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'
    }
  }
];

路由文件是static個文件,你在里面指定的數據也是。 所以 Angular 模板指令和表達式語言不會在那里被評估。

您可以改為在從路線讀取數據的位置翻譯翻譯鍵,我猜這類似於 header 元素。

使用ngx-translate ,這將通過使用TranslateService及其方法getinstant來實現,或者只是將翻譯鍵分配給組件字段,並在組件模板中以通常的方式使用translate pipe 。

你可以使用這個依賴: https://www.npmjs.com/package/@biesbjerg/ngx-translate-extract-marker

1-安裝依賴:

    ➜   npm i @biesbjerg/ngx-translate-extract-marker --save

2- 導入 dep 並使用它:

import { marker as _ } from "@biesbjerg/ngx-translate-extract-marker";

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

const routes: Routes = [
  {
    path: '',
    data: {
      title: _("NameEng")
    },
    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 {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM