Search code examples
angulartypescriptionic-frameworkngx-translateionic5

Apply param with the translate service and array of strings


This is from the doc:

translate.get('HELLO', {value: 'world'}).subscribe((res: string) => {
    console.log(res);
    //=> 'hello world'
});

How can I apply with the array like so?

 setPayPal(): void {
    this.translateService.get(['Client.Pay-With-PayPal', 'Client.Please-Click-And-Make-The-Payment',
     ]).subscribe(res => {
        this.payPal = {
          title: res['Client.Pay-With-PayPal'],
          payPalUrl: environment.payPalUrl,
          description: res['Client.Please-Click-And-Make-The-Payment'] 
        };
      });
  }

I can get that value like so: value: environment.parcelDeliveryCost

gr.json

"Please-Click-And-Make-The-Payment":"Bitte anklicken und die Bezahlung von {{value}} vornehmen",

So my question here is how to apply it with the array?


Solution

  • OP's Answer

    setPayPal(): void {
    
        forkJoin([this.translateService.get(['Client.Pay-With-PayPal', 'Client.Pay-Now']),
        this.translateService.get('Client.Please-Click-And-Make-The-Payment', { value: environment.parcelDeliveryCost })])
          .subscribe(([res1, res2]) => {
            this.payPal = {
              title: res1['Client.Pay-With-PayPal'],
              payPalUrl: environment.payPalUrl,
              description: res2,
              parentButtonText: res1['Client.Pay-With-PayPal'],
              childButtonText: res1['Client.Pay-Now'],
            };
          });
      }
    

    Original Answer

    You could trigger multiple observables using RxJS forkJoin, combineLatest or zip methods based on the nature of observables and requirement. Try the following

    forkJoin({
      'Client.Pay-With-PayPal': this.translateService.get('Client.Pay-With-PayPal'),
      'Client.Please-Click-And-Make-The-Payment': this.translateService.get('Client.Please-Click-And-Make-The-Payment')
    }).subscribe(
      response => {
        this.payPal = {
          title: response['Client.Pay-With-PayPal'],
          payPalUrl: environment.payPalUrl,
          description: response['Client.Please-Click-And-Make-The-Payment'] 
        };
      },
      error => {
        // handle error
      }
    );
    

    Note that forkJoin only emits when all the observables complete. If they are persistent observables and you wish to use only the first emitted values, you could use combineLatest method and pipe in a take(1) operator.

    One more thing, while forkJoin has an overload to accept plain objects as arguments (like shown above), the combineLatest and zip do not have them. The arguments should be an array.