Angular2路由器 - canActivate使用post请求重定向

时间:2016-11-03 03:55:20

标签: angular angular-ui-router angular2-routing

实施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;
    }
}

Browser Console

如果我删除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 ");
    }
}

1 个答案:

答案 0 :(得分:1)

检查的几个提示:

  1. 检查RouterModule.forRoot和RouterModule.forChild路由配置是否正确。
  2. 检查正在触发的默认网址。
  3. 检查按钮点击事件,路由器是否用于导航到下一页而不是使用表单按钮的默认行为(包括您使用表单)