SilverShroud
SilverShroud

Reputation: 56

Translate my Url Angular 2 - Typescript

Angular2 - TypeScript - ng-Translate

Hello people,

I need to change the rest of my url depending on language selected "en/soybean", "fr/soya". In my app.routes I got this path :

{ path: ':lang/soybean', component: SoybeanComponent }

My SoyBean component is translate from the lang param with ng-translate

this.route.params.subscribe(params => {
   translate.use(params['lang']);
})

How can I display the url as fr/soya but still use path fr/soybean !?

What I tried

*I create a new path: { path: ':lang/soya', component: SoybeanComponent }, I thought I could redirect the user to the good path :

 if(params['lang'] === 'en'){
       this.router.navigateByUrl('lang/soybean');
    }
    if(params['lang'] === 'fr'){
       this.router.navigateByUrl('lang/soya');
    }

but it will result on a infinite loading.
Then I thought I could hardcode the lang param after redirecting like :

if(params['lang'] === 'en'){
       this.router.navigateByUrl('en/soybean');
    }
    if(params['lang'] === 'fr'){
       this.router.navigateByUrl('fr/soya');
    }

but in this case I will catch an exception.*

Upvotes: 1

Views: 1063

Answers (2)

SilverShroud
SilverShroud

Reputation: 56

I found my own solution with location.replace(newUrl)

I create a new path : { path: ':lang/soya', component: SoybeanComponent }

and in my component I use location.replace(url)

 this.route.params.subscribe(params => {
            translate.use(params['lang']);
            switch (params['lang']) {
                case 'en':
                    location.replace(`index.html#/${params['lang']}/soybean`)
                        break;
                case 'fr':
                    location.replace(`index.html#/${params['lang']}/soya`);
                        break;
            }

        })

This works for me ! If you know a better solution i'll be glad to hear it ! Thx !

Upvotes: 0

JGFMK
JGFMK

Reputation: 8904

You are overcomplicating it :-). Just used template strings with backticks

url = `${lang}/${i18name}`

Upvotes: 1

Related Questions