我在mat-autocomplete中使用[displayWith]指令。当我手动选择值时它工作正常,但当我重新加载页面时,我没有得到翻译。转换所需的参数是从ngOnInit中的查询参数异步加载的。所以我依赖async参数,但我的displayFunction()是同步函数。怎么解决?
没有[displayWith]功能,一切正常,但没有翻译(它只是显示我不想要的纯值)。所以我确信其余的代码是正确的。
我的mat-autocomplete:
<mat-form-field [formGroup]="cityForm"
appearance="outline"
floatLabel="never"
color="primary">
<mat-icon matPrefix>location_on</mat-icon>
<input type="text" placeholder="{{ 'job_offer_search_bar.job-offer-search-bar-city-form.placeholder' | translate }}"
aria-label="Number" matInput
formControlName="cityControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="onSelectionChanged($event.option.value)"
[displayWith]="displayFn.bind(this)">
<mat-option>
{{ 'job_offer_search_bar.job-offer-search-bar-city-form.all' | translate }}
</mat-option>
<mat-option *ngFor="let city of filtredCities | async" [value]="city">
{{ 'job_offer_search_bar.job-offer-search-bar-city-form.city' | translate:"{ city: '" + city +"' }"}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
我的displayWith函数如下:
displayFn(val: string){
if (!val) return '';
let stringToReturn;
this.translate.get('job_offer_search_bar.job-offer-search-bar-city-form.city', {city: val}).subscribe(value => {
console.log('inside subscribe', value);
stringToReturn = value;
});
console.log('after sub', stringToReturn);
if (stringToReturn != undefined) {
return stringToReturn;
} else {
return 'Sorry, value has not been translated';
}
在Console.log in subscribe
之后援引console.log after subscribe
。所以订阅是在我得到我的参数进行翻译之后进行的,所以在我返回之后......我需要一些技巧或提示将我翻译的字符串作为返回传递。
我认为有办法做到这一点。任何帮助将不胜感激。
在大多数情况下,Observable是异步函数。根据您的实现,您可以使用translate.instant
displayFn(val: string) {
const defaultMessage = 'Sorry, value has not been translated';
return val
? this.translate.instant('job_offer_search_bar.job-offer-search-bar-city-form.city', { city: val }) || defaultMessage
: '';
}
如果在加载转换文件之前调用了即时函数,则它将返回undefined。
编辑:
displayFn(val: string) {
const translate$ = this.translate.get('job_offer_search_bar.job-offer-search-bar-city-form.city', { city: val }).pipe(
map(translatedText => translatedText || 'Sorry, value has not been translated')
)
return val
? translate$
: of('');
}
[displayWith]="displayFn.bind(this) | async"
解决这个问题很棘手。我不得不在mat-form-field上使用* ngIf来等待我的翻译标签:
<mat-form-field *ngIf="isReady$ | async" [formGroup]="cityForm"
翻译完成后应该满足条件所以我必须在ngOnInit中执行此操作:
this.isReady$ = this.translate.get('translate_id').pipe(mapTo(true));
因此,在从翻译服务返回翻译之前,现在不显示元素。这是一种解决方法,但我还没有找到其他解决方案。