以角度转换动态值?

问题描述 投票:0回答:1

我想知道是否可以将动态值转换为角度。例如,有一个用于创建新帖子的字段。您输入帖子名称。现在你用你的语言输入了,但是当你切换应用程序的语言时,如何才能实现你输入的名称被翻译成切换后的语言呢?

我用了NGX翻译

现在我读到了翻译 API

但我想知道是否有一个简单的解决方案?

或者我可以使用不同的方式在前端输入值(例如名称)并动态翻译它们吗?

angular internationalization ngx-translate
1个回答
0
投票

处理动态内容翻译的方法

  • 根据您的代码结构更新代码
  • 安装依赖项:
npm install @ngx-translate/core @ngx-translate/http-loader

在模板中使用

dynamicTranslate
管道:

<h1>{{ dynamicContentId | dynamicTranslate | async }}</h1>
// translation.service.ts
import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

interface TranslationEntry {
  id: string;
  translations: {
    [key: string]: string;  // language code -> translated text
  };
}

@Injectable({
  providedIn: 'root'
})
export class DynamicTranslationService {
  private translationsSubject = new BehaviorSubject<TranslationEntry[]>([]);
  public translations$ = this.translationsSubject.asObservable();

  constructor(
    private translate: TranslateService,
    private http: HttpClient
  ) {
    // Initialize translations from storage or API
    this.loadTranslations();
  }

  // Add new content with translations
  addDynamicContent(content: string, sourceLanguage: string): string {
    const id = this.generateUniqueId();
    const translations = {
      [sourceLanguage]: content
    };

    // Store the new entry
    const currentTranslations = this.translationsSubject.value;
    currentTranslations.push({ id, translations });
    this.translationsSubject.next(currentTranslations);

    // Optionally, send to backend
    this.saveToDB({ id, translations });

    return id;
  }

  // Get translated content
  getTranslation(id: string, targetLanguage: string): Observable<string> {
    return this.translations$.pipe(
      map(translations => {
        const entry = translations.find(t => t.id === id);
        if (!entry) return id; // fallback to ID if not found

        // If translation exists, return it
        if (entry.translations[targetLanguage]) {
          return entry.translations[targetLanguage];
        }

        // If translation doesn't exist, try to translate
        return this.translateContent(
          entry.translations[Object.keys(entry.translations)[0]],
          targetLanguage
        );
      })
    );
  }

  // Translate using external service (example using Google Translate API)
  private async translateContent(text: string, targetLanguage: string): Promise<string> {
    // Implementation would depend on your chosen translation API
    // Example using a translation service:
    const apiUrl = `your-translation-api-endpoint`;
    const response = await this.http.post(apiUrl, {
      text,
      targetLanguage
    }).toPromise();

    return response['translatedText'];
  }

  private generateUniqueId(): string {
    return 'dyn_' + Math.random().toString(36).substr(2, 9);
  }

  private loadTranslations() {
    // Load from localStorage or API
    const stored = localStorage.getItem('dynamicTranslations');
    if (stored) {
      this.translationsSubject.next(JSON.parse(stored));
    }
  }

  private saveToDB(entry: TranslationEntry) {
    // Save to backend/database
    const currentTranslations = this.translationsSubject.value;
    localStorage.setItem('dynamicTranslations', JSON.stringify(currentTranslations));
  }
}
// example-component.ts
import { Component, OnInit } from '@angular/core';
import { DynamicTranslationService } from './dynamic-translation.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-post-creator',
  template: `
    <!-- Create Post Form -->
    <form (ngSubmit)="createPost()">
      <input [(ngModel)]="postName" name="postName" placeholder="Enter post name">
      <button type="submit">Create Post</button>
    </form>

    <!-- Display Posts -->
    <div *ngFor="let post of posts">
      <h3>{{ post.translationId | dynamicTranslate | async }}</h3>
    </div>
  `
})
export class PostCreatorComponent implements OnInit {
  posts: Array<{ id: string, translationId: string }> = [];
  postName: string = '';

  constructor(
    private dynamicTranslationService: DynamicTranslationService,
    private translateService: TranslateService
  ) {}

  createPost() {
    // Store the post name with current language
    const translationId = this.dynamicTranslationService.addDynamicContent(
      this.postName,
      this.translateService.currentLang
    );

    // Add post to list
    this.posts.push({
      id: Math.random().toString(),
      translationId
    });

    this.postName = '';
  }
}
// dynamic-translate.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { DynamicTranslationService } from './dynamic-translation.service';
import { TranslateService } from '@ngx-translate/core';
import { Observable } from 'rxjs';

@Pipe({
  name: 'dynamicTranslate'
})
export class DynamicTranslatePipe implements PipeTransform {
  constructor(
    private dynamicTranslationService: DynamicTranslationService,
    private translateService: TranslateService
  ) {}

  transform(translationId: string): Observable<string> {
    return this.dynamicTranslationService.getTranslation(
      translationId,
      this.translateService.currentLang
    );
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.