首页 文章

Angular 2 RC4路由器提供商

提问于
浏览
2

我目前正在更新我的应用程序以使用ner Router . 除保护路线外,我做了一切 .

主要 . ts看起来像这样:

import {bootstrap} from '@angular/platform-browser-dynamic';
import {disableDeprecatedForms, provideForms} from '@angular/forms';
import {HTTP_PROVIDERS} from '@angular/http';
import 'rxjs/Rx';

import {AuthService} from './services/auth.service';

import {AppComponent} from './app.component';

import {AuthGuard} from './services/auth.guard'

bootstrap(AppComponent, [appStateProvider, APP_ROUTER_PROVIDERS, AuthService, AuthGuard, HTTP_PROVIDERS,,disableDeprecatedForms(), provideForms()])
.catch(err => console.error(err));

我实现了auth.guard.ts:

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private _authService: AuthService, protected _router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {

        if (state.url !== '/login' && !this._authService.isLoggedIn()) {
            this._router.navigate(['/login']);
            return false;
        }

        return true;
    }
}

在我的应用程序路线:

export const routes: RouterConfig = [
   {
    path: '',
    component: LoginComponent 
  },  
  { path: 'login', component: LoginComponent },
  { path: 'home', component: HomeComponent, canActivate: ['AuthGuard']}
];

// Export routes
export const APP_ROUTER_PROVIDERS = [
  provideRouter(routes)
];

在此之前,我使用旧的路由,一切都很好 . 现在,我得到了麻烦'没有AuthGuard提供商!'我将它包含在我的引导程序提供程序中 .

在我的app.component.ts里面构造函数我有:

if (this._authService.isLoggedIn()) {
      this._router.navigate(['/home']);
    }
    else {
      this._router.navigate(['/login']);
    }

在我更新路由器之前如果用户没有登录,它会重定向到登录页面,否则它会重定向到主页,用户在他没有登录之前无法看到家 . 我在哪里错了,为什么我从此收到此错误我在我的bootstrap方法中包含提供者作为提供者?

谢谢

1 回答

  • 3

    从中删除 '

    canActivate: ['AuthGuard']},
    

    canActivate: [AuthGuard]},
    

    我也认为你应该添加 pathMatch: 'full'

    {
        path: '',
        component: LoginComponent,
        pathMatch: 'full' 
      },
    

相关问题