Угловая - 404 при переходе на другой компонент - PullRequest
0 голосов
/ 15 января 2019

Приложение My Angular 6 содержит контент, который пользователь вошел в систему для просмотра. Поэтому у меня есть AuthGuard, реализующий интерфейс CanActivate, который перенаправляет на страницу входа в отрицательном регистре.

Когда я вызываю router.navigate внутри моего AuthGuard, целевой компонент (Login) вызывается и инициализируется (вызывается конструктор). Но затем отображается 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 / release' и вызывает AuthGuard. Он перенаправляет на страницу входа в систему, потому что пользователь в настоящий момент не вошел в систему. Я установил точку останова в конструкторе компонента входа в систему, и отладчик остановился на этом этапе. Итак, знайте, что компонент называется.

Это URL, отображаемый в браузере: http://localhost:8080/pmt/login?returnUrl=%2Fpages%2Freleases

Но отображаемая страница содержит 404: тип: отчет о состоянии сообщение: / pmt / логин описание: запрошенный ресурс недоступен

...