1

Im trying to create a Guard service to authenticate my routes. But my guard service are located in a shared library.

This is my guard service:

@Injectable({
  providedIn: 'root'
})
export class RouteGuard implements CanActivate {
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
    return true;
  }
  
}

Provided at shared modules:

import {RouteGuard} from './auth/guard/route.guard';

@NgModule({
  imports: [CommonModule, MaterialModule],
  exports: [MaterialModule],
  providers: [RouteGuard]
})
export class SharedModule {}

And now i need to get this provided service at app module. How can i do that?

import {SharedModule} from '@acn-collections-ws/shared';

@NgModule({
  declarations: [AppComponent, AuthComponent, LoggedComponent, HomeComponent, LoginComponent, SigninComponent],
  imports: [BrowserModule, BrowserAnimationsModule, AppRoutingModule, SharedModule],
  providers: [],
  bootstrap: [AppComponent],
  exports: [
    AuthComponent,
    LoggedComponent,
    HomeComponent,
    LoginComponent,
    SigninComponent
  ],
})
export class AppModule {}

i need to import this service in my app routing module, and use with canActivate route validator. Like this:

// i cant found RouteGuard at acn-collections-ws/shared
import { RouteGuard } from '@acn-collections-ws/shared';
const routes: Routes = [
  {
    path: '',
    component: LoggedComponent,
    children: [
      {path: '', component: HomeComponent}
    ],
    canActivate: [RouteGuard]
  },
  {
    path: '',
    component: AuthComponent,
    children: [
      {path: '', redirectTo: 'login', pathMatch: 'full'},
      {path: 'login', component: LoginComponent},
      {path: 'signin', component: SigninComponent}
    ]
  }

];
Flávio Costa
  • 895
  • 5
  • 18
  • 41

1 Answers1

1

Ok, i found it.

@NgModule({
  imports: [CommonModule, MaterialModule],
  exports: [MaterialModule],
  providers: [RouteGuard]
})
export class SharedModule {}

from the index.ts of shared library i need to export guard.module. (I was not exporting guard module).

export * from './lib/guard.module';

And know it worked

// Service guard
import {RouteGuard} from '@acn-collections-ws/shared';
Flávio Costa
  • 895
  • 5
  • 18
  • 41