bellotas
bellotas

Reputation: 2461

Different URL depending on the language - Angular 2

I have a translation.service.ts to show my website in different languages. That works. Now I would like to add to the URL something like /es/ or /en/ depending on the language shown.

My service is:

import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Injectable()
export class TranslationService {
    constructor(
        //Used for the internationalization
        private translate: TranslateService,
    ) { }

        switchLanguage(language: string) {
            //If spanish
            if (
             language == "es" || language == "es-ar" || language == "es-bo" || language == "es-cl" ||
             language == "es-co" || language == "es-cr" || language == "es-do" || language == "es-ec" ||
             language == "es-sv" || language == "es-gt" || language == "es-hn" || language == "es-mx" ||
             language == "es-ni" || language == "es-pa" || language == "es-py" || language == "es-pe" ||
             language == "es-er" || language == "es-es" || language == "es-uy" || language == "es-ve") this.translate.use("es");
            //If german
            else if (language == "de" || language == "de-at" || language == "de-de" || language == "de-li" || language == "de-lu" || language == "de-ch" ) this.translate.use("de");
            //if not, english 
            else this.translate.use("en");
        }
    }

Update: 13/02/2018

I have tried:

app-routing.module.ts

var language = navigator.language;
const routes: Routes = [
  { path: '', redirectTo: '/dashboard/'+language, pathMatch: 'full'},
  { path: 'dashboard/'+language, component: DashboardComponent },
}

but I get an error:

ERROR Error: Uncaught (in promise): Error: Cannot redirect to '/dashboard/:language'. Cannot find ':language'. Error: Cannot redirect to '/dashboard/:language'. Cannot find ':language'.

and when I try:

const routes: Routes = [
  { path: '', redirectTo: '/dasboard/:language', pathMatch: 'full'},
  { path: 'dashboard:language', redirectTo: '/dasboard/:language', component: DashboardComponent }
]

I get:

Error: Invalid configuration of route 'dashboard:language': redirectTo and component cannot be used together

Any suggestion?

Upvotes: 1

Views: 2198

Answers (1)

Aravind
Aravind

Reputation: 41571

Set the route param and navigate to the url

this.router.navigate(['../', { language: language}]

You should have the route configuration to contain the language as parameter shown below

 { path: '.../:language', redirectTo: '/..../:language' },

Upvotes: 1

Related Questions