实施CanActivate以保护路由,并在用户未登录时导航到/ login,但我可以看到它正在使用POST请求重定向,这导致404错误。
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate() {
console.log("canActivate : AuthGuard");
if (localStorage.getItem('currentUser')) {
// logged in so return true
return true;
}
// not logged in so redirect to login page
this.router.navigate(['/login']);
return false;
}
}
如果我删除AuthGuard,它会正确重定向。任何人都可以帮助我。
app.routes.ts
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {HomeComponent} from './home/home.component';
import {DashBoardComponent} from './dashboard/dashboard.component';
import { AuthGuard } from './guards/auth.guard';
const appRoutes: Routes = [
{
path: 'login',
component: LoginComponent
},
{
path: 'home',
component: HomeComponent,
canActivate: [AuthGuard],
children: [
{ path: 'dashboard', component: DashBoardComponent }
]
}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
app.module.ts
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
@NgModule({
imports: [ BrowserModule ,routing , CKEditorModule,FormsModule, HttpModule, ReactiveFormsModule, TagInputModule],
declarations: [ AppComponent , DashBoardComponent,LoginComponent,HomeComponent],
providers: [AuthGuard, AuthenticationService, {provide: LocationStrategy, useClass: HashLocationStrategy}],
bootstrap: [ AppComponent]
})
export class AppModule { }
app.component.ts
import { Component, OnInit } from '@angular/core';
import {DashBoardComponent} from './dashboard/dashboard.component';
import {LoginComponent} from './login/login.component';
import {HomeComponent} from './home/home.component';
@Component({
selector: 'app',
template: `<router-outlet></router-outlet>`,
precompile: [LoginComponent]
})
export class AppComponent implements OnInit {
ngOnInit() {
console.log("checkking ");
}
}
答案 0 :(得分:1)
检查的几个提示: