简体   繁体   中英

How to get a provided service from shared library in AppModule level? Angular

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}
    ]
  }

];

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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM