Angular 2 - 页面加载时的许多历史条目

时间:2017-06-08 00:43:06

标签: angular angular-routing

当我在新的浏览器窗口中打开我的Angular 2应用程序时,我在浏览器页面历史记录中获得10个条目。这发生在路由器中列出的任何页面上,没有指定页面(即http://localhost:8080http://localhost:8080/survey等)

const routes: Routes = [
    {path: 'survey', component: SurveyComponent, canActivate: [AuthGuard]},
    {path: 'survey/:id', component: SurveyComponent, canActivate: [AuthGuard]},
    {path: '', component: HomeComponent},
    {path: 'about', component: AboutComponent},
    {path: 'terms', component: TermsAndConditionsComponent},
    {path: 'map', component: MapComponent},
    {path: 'what-next', component: WhatNextComponent},
    {path: 'contact', component: ContactComponent},
    {path: '**', redirectTo: '', pathMatch: 'full'},
];

我正在使用路由器3.1.2

"@angular/router": "3.1.2",

enter image description here

我从去年3月开始发现similar question,但答案声称已经在Angular的代码中解决了。

更新 根据要求,这是AuthGuard代码

import {Injectable} from '@angular/core';
import {AuthenticationService} from '../_services/index';
import {LoginModalService} from "../login_modal/login_modal.service";
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private authentication: AuthenticationService, private loginModalService: LoginModalService) {
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (this.authentication.isAuthenticated()) {
            return Observable.of(true);
        } else {
            this.loginModalService.toggleVisable(state.url);
            return Observable.of(false);
        }
    }
}

1 个答案:

答案 0 :(得分:3)

我有类似的情况,我通过延迟加载路线解决了它 也就是说,您可以将路径分离到主要路径加载中的不同模块路由广告,如thi

在主要路线

      {
        path: 'dashboard',
        component: DashboardComponent,
      },
      {
        path: 'user',
        loadChildren: 'app/user/user.module#UserModule',  //in user module
      },

在用户模块中你可以

@NgModule ( {
  imports: [
   userRoutingModule //contains my user module routes
  ] ,

 } )
export class UserModule {

 }

用户路由模块

const userRoutes: Routes = [
        { path: '', component: UserComponent},
     ];

 @NgModule({
  imports: [
    RouterModule.forChild(userRoutes)
   ],

   exports: [RouterModule],
     providers: []
   })
 export class userRoutingModule { }

这就是我如何解决我的问题,我希望这会有所帮助。

注意:记住import.forRoot的主要路线

在这种情况下,请确保在根模块(probly app module中导入用户模块)

  @NgModule({
    declarations: [
    ],

  imports: [

    UserModule,  //in your case maybe use survey module

    ],

   })

  export class AppModule {}  //this is in my root module