我目前已更新我的應用以使用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'上將它添加爲默認參數。 –