I use a notification.service.ts file that looks like this:
import {Injectable} from '@angular/core';
import {ToastController} from "@ionic/angular";
import {TranslateService} from '@ngx-translate/core';
/**
* Stateless service that shows UI notifications.
*/
@Injectable({providedIn: 'root'})
export class NotificationService {
isToastVisible = false;
constructor(private toastController: ToastController, private translate: TranslateService) {
}
async showSuccess(message: string) {
await this.presentToast('success', this.translate.instant(message));
}
async showWarning(message: string) {
await this.presentToast('warning', this.translate.instant(message));
}
async showError(message: string) {
await this.presentToast('danger', this.translate.instant(message));
}
async dismissToast() {
await this.toastController.dismiss();
}
private async presentToast(color: string, message: string) {
if (this.isToastVisible) return;
this.isToastVisible = true;
await this.toastController.create({
color: color,
message: message,
position: 'top',
buttons: [
{
text: 'x',
role: 'cancel',
}
]
}).then((toast: HTMLIonToastElement) => {
toast.onDidDismiss().then(() => {
this.isToastVisible = false;
});
toast.present();
});
}
}
Then, in for example a page component like register.page.ts I do the following:
import {NotificationService} from '../../services/notification.service'; // on top of file
export class RegisterPage implements OnInit {
constructor(
private notificationService: NotificationService,
) {
}
// a service that calls an API
async getFunctions(): Promise<void> {
this.api.getFunctions()
.then(async data => {
this.Userfunctions = data;
}).catch((error: Error | HttpErrorResponse) => {
if (error instanceof HttpErrorResponse) {
this.notificationService.showError(`error_service_functions`);
}
else {
throw error;
}
});
}
}
The key of the translation is sent here:
this.notificationService.showError(`error_service_functions`);
And gets translated via ngx-translate. The result is a multilingual toast message: