我发送了一个请求,要求从“ assets”文件夹中加载i18n.json文件和一些图像,但只是收到404找不到。我需要在webpack.config.json中添加任何内容吗?如果需要,情况如何?
注意:我没有使用Angular-cli,所以没有从root配置资产的angular.json。
translationsUrl = '/assets/i18n/header';
loadTranslations(locale: string) {
return this.http.get(`${this.translationsUrl}/${locale}.json`).subscribe((data: any) => {
});
}
答案 0 :(得分:0)
您是否尝试过在angular.json中指定它,如下所示:
"assets": [
...
"src/assets/i18n/header/vn.json",
"src/assets/i18n/header/en.json",
]
答案 1 :(得分:0)
您无法以这种方式加载json,因为它将无法正常工作。您需要将其设置为承诺加载该文件。我忘记了原因。但是,去年我通过此解决方案解决了该问题。
我写了一篇关于它的文章-Add internationalization (i18n) to an Angular app
尝试:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class TranslateService {
translateObject: any = {};
constructor(private http: HttpClient) {}
loadTranslations(lang: string = 'en'): Promise<{}> {
return new Promise<{}>((resolve, reject) => {
const langPath = `assets/i18n/header/${lang}.json`;
this.http.get(langPath).subscribe(
translation => {
this.translateObject = translation;
resolve(this.translateObject);
},
error => {
this.translateObject = {};
resolve(this.translateObject);
}
);
});
}
}
然后添加一个translate
管道:
import { Pipe, PipeTransform } from '@angular/core';
import { TranslateService } from 'src/app/shared/services/translate.service';
@Pipe({
name: 'translate',
pure: false
})
export class TranslatePipe implements PipeTransform {
constructor(private translate: TranslateService) {}
transform(key: any): any {
return this.translate.translateObject[key] || key;
}
}