John John - 2 months ago 49
Javascript Question

Angular2 - No provider for LoggedInGuard

I'm making a Anuglar2 rc-4 web application. I'm trying to restrict routes but when i add my login guard, it tells me there is no provider. My normal login service code works fine, its just when i try to add the login guard and canActive routes. Any ideas on how to fix this error?

routes.ts

import { RouterConfig } from '@angular/router';
import { Home } from './components/home/home';
import { Login } from './components/login/login';
import { DashBoard } from './components/dashboard/dashboard';
import { User } from './components/user/user';
import { Store } from './components/store/store';
import { LoggedInGuard } from './models/logged-in.guard.ts';

export const routes: RouterConfig = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: Home, canActivate: [LoggedInGuard] },
{ path: 'login', component: Login },
{ path: 'dashboard', component: DashBoard },
{ path: 'user', component: User },
{ path: 'store', component: Store },
{ path: '**', redirectTo: 'home' }
];


boot.ts

import { bootstrap } from '@angular/platform-browser-dynamic';
import { FormBuilder } from '@angular/common';
import { provideRouter } from '@angular/router';
import { HTTP_PROVIDERS, JSONP_PROVIDERS } from '@angular/http';
import { App } from './components/app/app';
import { routes } from './routes';

bootstrap(App, [
HTTP_PROVIDERS,
FormBuilder,
provideRouter(routes)
]);


logged-in.guard.ts

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { LoginService } from '../services/login.service';

@Injectable()
export class LoggedInGuard implements CanActivate {
constructor(private ls: LoginService) {}

canActivate() {
return this.ls.isLoggedIn();
}
}

Answer

You have to inject your LoggedInGuard service inside your application bootstrap function

bootstrap(App, [
    HTTP_PROVIDERS,
    FormBuilder,
    provideRouter(routes),
    LoggedInGuard // injected LoggedInGuard service provider here
]);

Note: This answer would not be the same for the current angular 2 updated version(rc.6), When you upgrade you need to create a NgModule where you are going to wrap up all the dependencies in single place, that time LoggedInGuard will go inside providers option of `NgModule

`

Comments