简体   繁体   中英

Angular 6 Lazy Loading routes navigation on page refresh

I am working on angular 6 lazy loading and stuck in a problem. can't find any solution yet.

My poblem is :

I have a sign in page that i can load on starting on the application after signing in there is a home page having a single select drop down with two options on select on first option Firstcomponent will load(First component have some info) and on select on second option SecondComponent will load(Second component also have some info) under select dropdown. Now my problem is when refresh on that page ie http://localhost:4300/home/first after refresh select dropdown and first component load as same but select dropdown field is shown blank here and want to selected with first option. is there any solution for this.

Thanks in advance.

Here is my code.

app.routing.module.ts

const routes: Routes = [
    {
        path: "",
        redirectTo: "/signIn",
        pathMatch: 'full'
    }, {
        path: "signIn",
        component: SignInComponent
    }, {
        path: "home",
        loadChildren: () => HomeModule
    }, {
        path: "**",
        redirectTo: "/signIn",
        pathMatch: 'full'
    }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})

export class AppRoutingModule { }

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    SignInComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HomeModule 
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

HomeModule.ts

@NgModule({
    imports: [
        CommonModule,
        HomeRoutingModule
    ],
    declarations: [
        HomeComponent,
        FirstComponent,
        SecondComponent
    ]
})
export class HomeModule { }

home.routing.module.ts

const routes: Routes = [
    {
        path: "",
        component: HomeComponent,
        children: [{
                path: 'first',
                component: FirstComponent
            },{
                path: 'second',
                component: SecondComponent
            }]
    }
];

@NgModule({
    exports: [RouterModule],
    imports: [RouterModule.forChild(routes)]
})
export class HomeRoutingModule{ }

home.component.ts

@Component({
  template: '<select (change)="selectedComponent($event.target.value)">
          <option value="First">First</option>
          <option value="Second">Second</option>
        </select>'
})
export class HomeComponent {
  private selectedComponent(selectedValue: string): void {
    if (selectedValue === "First")
      this.router.navigate(['/home/first']);
    else
      this.router.navigate(['/home/second']);
  }
}

您应该注入ActivatedRoute或RouterState对象以获取活动路由,并在选择的内容中选择好选项。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM