简体   繁体   English

如何从 AppModule 级别的共享库中获取提供的服务? Angular

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

Im trying to create a Guard service to authenticate my routes.我试图创建一个 Guard 服务来验证我的路由。 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.现在我需要在 app 模块中获得这个提供的服务。 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.我需要在我的应用路由模块中导入此服务,并与 canActivate 路由验证器一起使用。 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.从共享库的 index.ts 我需要导出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';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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