我目前已更新我的应用以使用ner Router。除了保护路线,我做了所有事情Angular 2 RC4路由器提供商
main。 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 {InsaService } from './services/insa.service';
import {AppComponent} from './app.component';
import {appStateProvider} from './providers/AppStateProvider'
// Import configured routes
import { APP_ROUTER_PROVIDERS } from './app.routes';
import {AuthGuard} from './services/auth.guard'
bootstrap(AppComponent, [appStateProvider, APP_ROUTER_PROVIDERS, AuthService, AuthGuard, HTTP_PROVIDERS, InsaService ,disableDeprecatedForms(), provideForms()])
.catch(err => console.error(err));
我implementeed 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']},
{ path: 'charts', component: ChartsComponent},
{ path: 'performance', component: PerformanceComponent},
{ path: 'news', component: NewsComponent},
{ path: 'transactions', component: TransactionsComponent},
{ path: 'portfolio', component: PortfolioComponent},
{ path: 'crossRates', component: CrossRatesComponent},
{ path: 'report', component: ReportComponent},
{ path: 'security', component: SecurityPricesComponent},
];
// Export routes
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];
,我用旧的路由和一切罚款之前。现在,我得到了消息“没有AuthGuard的提供者!” althoug我将它包含在我的引导程序提供程序中。
在我里面的构造app.component.ts我:
if (this._authService.isLoggedIn()) {
this._router.navigate(['/home']);
}
else {
this._router.navigate(['/login']);
}
我更新路由器之前,如果用户不是在它登陆重定向到登录页面,否则它重定向到主页和用户couldn” t直到他没有登录才看到家。我在哪里我错了,为什么我得到这个错误,因为我包含供应商在我的引导方法作为提供者?
感谢
第一次发生这种情况,我,这个问题实际上回答了我的问题。感谢您的'auth.guard.ts'代码,我能够解决我有'canActiate(...)'的问题。我在构造函数中添加了'ActivatedRouteSnapshot',但看起来这是错误的方法,在'canActivate'上将它添加为默认参数。 –