角度-导航到其他组件时为404

时间:2019-01-15 12:52:43

标签: angular angular2-routing

我的Angular 6应用程序包含用户已登录查看的内容。因此,我有一个实现CanActivate接口的AuthGuard,如果情况不佳,它将重定向到登录页面。

当我在AuthGuard中调用router.navigate时,将调用并初始化目标组件(登录)(将调用构造函数)。但是随后会显示404。

app.routing.ts:

export const routes: Routes = [
  { path: '', redirectTo: 'pages/releases', pathMatch: 'full', canActivate: [AuthGuard] },
  { path: 'login', component: Login },
  { path: '**', redirectTo: '' },
];

注意:“页面”确实具有自己的路由设置:

export const routes: Routes = [
{
    path: 'pages',
    component: Pages,
    canActivate: [AuthGuard],
    canActivateChild: [AuthGuard],
    children: [
      { path: '', redirectTo: './releases/releases.module#ReleasesModule', pathMatch: 'full' },
  { path: 'employees', loadChildren: './employees/employees.module#EmployeesModule' },
  { path: 'releases', loadChildren: './releases/releases.module#ReleasesModule' },
  { path: 'strategies', loadChildren: './strategies/strategies.module#StrategiesModule' }
    ]
  }
];

auth.guard.ts:

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private router: Router,
          private zone: NgZone) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)     
    {
        if (localStorage.getItem('currentUser')) {
              // logged in so return true
              return true;
        }

        // not logged in so redirect to login page with the return url
        this.zone.run( () =>
          this.router.navigate(['login'], { queryParams: { returnUrl: state.url } }));

        return false;
      }
}

login.ts

@Component({
  selector: 'login',
  templateUrl: './login.html',
  providers: [AuthenticationService]
})
export class Login {

  email = new FormControl();
  ...

  constructor(private route: ActivatedRoute,
          private router: Router,
          private authenticationService: AuthenticationService) {

    // reset login status
    this.authenticationService.logout();

    // get return url from route parameters or default to '/'
    this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
  }

  onSubmit(values: Object): void { ... }
}

打开'localhost:8080 / pmt'重定向到'pages / releases',并调用AuthGuard。由于用户当前未登录,它重定向到Login-Page。我在Login-Component构造函数中设置了一个断点,并且调试器此时已停止。所以知道该组件叫做。

这是浏览器中显示的URL:      http://localhost:8080/pmt/login?returnUrl=%2Fpages%2Freleases

但是显示的页面包含404: 类型:状态报告 讯息:/ pmt / login 说明:请求的资源不可用

0 个答案:

没有答案