user2548436
user2548436

Reputation: 925

Always Redirected To Home On Language Change - Angular2 with Localize-Router

I'm working on an Angular2 app, which use ngx-translate for text translation and localize-router in order to append the language to the route URL.

Now, without using localize-router, everything is working fine and I can change language (via dropdown button) and see text translations applied.

After installing localize-router, if I load the home page, I can see that the language is correctly appended to the URL. But the problem is that when I change the language, the component (localize-router) redirect the user to the homepage (with the new language name append to the URL) instead of remaining to the current page.

So at website loading the language is correctly appended, if I try to navigate, the URL are correctly translated, but when I'm on a page different from the home and I try to change the language, I'm redirected to the home page with the new language appended.

Here there are my files and configs:

app.module.ts

@NgModule({
imports: [
 TranslateModule.forRoot({
        loader: {
            provide: TranslateLoader,
            useFactory: (createTranslateLoader),
            deps: [Http]
        }
    }),
    
    RouterModule.forRoot(routes,{useHash: true}),
    LocalizeRouterModule.forRoot(routes),

app.routes.ts

const appRoutes: Routes = [
{

    path: '', 
    component: DefaultLayoutComponent,
    children: [
        {
            path: '',
            component: HomeComponent,
            pathMatch: 'full'
        },
        {
            path: 'error',
            component: ErrorComponent
        },
        {
            path: 'dashboard',
            children: [
                {
                    path: 'home',
                    component: DashboardComponent,
                    canActivate: [AuthGuard]
                },

app.component.ts

@Component({
selector: 'my-app',
template: '<router-outlet></router-outlet>',    
moduleId: module.id,
})


 export class AppComponent implements OnInit {

constructor(
    private translate: TranslateService,
    public router: Router,
   
) {
   
    this.translate.addLangs(['ita', 'eng']);
    this.translate.setDefaultLang('ita');
    this.translate.use('ita');

DefaulLayoutComponent.html

... my html common section ...
<router-outlet></router-outlet>
... the remaining common html section ...

topbar.component.ts It handles the menu bar, when i click on dropdown the following function (inside topbar component) is called:

changeLanguage(lang: string){
  this.translate.use(lang);
  this.localizeService.changeLanguage(lang);

topbar.component.html (I just wrote the button template)

<button (click)="changeLanguage('ita')">ITA</button>
<button (click)="changeLanguage('eng')">ENG</button>

Folder Structure

- app
  - app.module.ts
  - app.component.ts
  - other "main" stuff
  - components
    - defaultLayout
      - defaultLayoutComponent.ts
      - defaultLayoutComponent.html
    - other components

The version of software used are:

"@angular/common": "~2.4.1",
"@angular/compiler": "~2.4.1",
"@angular/compiler-cli": "~2.4.1",
"@angular/core": "~2.4.1",
"@angular/forms": "~2.4.1",
"@angular/http": "~2.4.1",
"@angular/platform-browser": "~2.4.1",
"@angular/platform-browser-dynamic": "~2.4.1",
"@angular/platform-server": "~2.4.1",
"@angular/router": "~3.2.3",
"@angular/upgrade": "~2.4.1",   
"@ngx-translate/core": "^6.0.1",
"@ngx-translate/http-loader": "^0.1.0",
"localize-router": "^0.7.1",

I cannot upgrade from angular2 to angular4 or greather.

So what I'm doing wrong?

Why when I'm for example in this page:

http://mywebsite/#/ita/login

and I change the language I'm redirected to

http://mywebsite/#/eng ?

I'm guessing if the problem could be in my route configuration, if I print a toString of the ActivatedRouteSnapshot object (independently from the current page) I always get

  Route(url:'', path:'')

Upvotes: 4

Views: 4295

Answers (3)

user2548436
user2548436

Reputation: 925

As I was thinking, the problem is in the routes configuration, in fact I have created DefaultLayoutComponents just to have a common layout for all the pages.

The solution is to delete DefaultLayoutComponent, move all the view code into app.component.html and modify the route config removing the level of DefaultLayoutComponent in this way:

const appRoutes: Routes = [
{
    {
        path: '',
        component: HomeComponent,
        pathMatch: 'full'
    },
    {
        path: 'error',
        component: ErrorComponent
    },
    {
        path: 'dashboard',
        children: [
            {
                path: 'home',
                component: DashboardComponent,
                canActivate: [AuthGuard]
            },

Because the localized-route make use ActivatedRouteSnapshot looping on the children of the route.

With the previous routes configurations, the children of DefaultLayoutComponents seems to be empty.

Upvotes: 0

Michael W. Czechowski
Michael W. Czechowski

Reputation: 3457

Try to stick to the working example and documentation of localize-router repository. Reduce your changeLanguage() function to:

changeLanguage(lang: string){
  this.localizeService.changeLanguage(lang);
}

Documentation

changeLanguage(lang: string, extras?: NavigationExtras, useNavigateMethod?: boolean): Translates current url to given language and changes the application's language. extras will be passed down to Angular Router navigation methods. userNavigateMethod tells localize-router to use navigate rather than navigateByUrl method. For german language and route defined as :lang/users/:user_name/profile

Source

Upvotes: 0

Michael W. Czechowski
Michael W. Czechowski

Reputation: 3457

Change topbar.component.js to this:

changeLanguage(lang: string){
  this.translate.use(lang);
  this.localizeService.translateRoute(this.router.url);
}

This will translate the given route instead of redirecting to the document root /. And this.router.url returns the current path, where your user is currently is.

Finally do not forget to add router as a dependency to your topbar component.

Upvotes: 1

Related Questions