Reputation: 279
I'm currently updated my app to use ner Router. I did everything except protected routes.
main. ts looks like this:
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));
I 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;
}
}
and in app routes I have:
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)
];
Before that I used old routing and everything fine. Now, I got messsage 'No provider for AuthGuard!' althoug I include it in my bootstrap providers.
In my app.component.ts inside constructor I have:
if (this._authService.isLoggedIn()) {
this._router.navigate(['/home']);
}
else {
this._router.navigate(['/login']);
}
Before I updated router if User wasn't logged in it redirected to login page, else it redirected to home page and user couldn't see home until he is not logged in. Where I'm I wrong and why I get this error since I included provider in my bootstrap method as provider?
Thanks
Upvotes: 2
Views: 457
Reputation: 658067
Remove the '
from
canActivate: ['AuthGuard']},
to
canActivate: [AuthGuard]},
I also think you should add pathMatch: 'full'
to
{
path: '',
component: LoginComponent,
pathMatch: 'full'
},
Upvotes: 3