【问题标题】:How to get a provided service from shared library in AppModule level? Angular如何从 AppModule 级别的共享库中获取提供的服务?角
【发布时间】:2021-08-09 04:38:24
【问题描述】:

我正在尝试创建一个 Guard 服务来验证我的路由。但我的守卫服务位于共享库中。

这是我的警卫服务:

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

在共享模块中提供:

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

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

现在我需要在 app 模块中获得这项提供的服务。我该怎么做?

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

我需要在我的应用路由模块中导入此服务,并与 canActivate 路由验证器一起使用。像这样:

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

];

【问题讨论】:

  • 你为什么在'@acn-collections-ws/shared' 中寻找RouteGuard ?不是来自'some_way/auth/guard/route.guard' 吗?
  • 我的守卫位于共享库@acn-collections-ws/shared
  • 我正在使用 @nwrl 库 --preset=angular。有了这个,我可以使用@ 导入外部库
  • 你能创建一个最小的可验证stackblitz 示例吗?
  • 我今天以后会尝试这样做。谢谢兄弟!

标签: javascript angular angular-ui-router ng-modules


【解决方案1】:

好的,我找到了。

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

我需要从共享库的 index.ts 导出guard.module。 (我没有导出保护模块)。

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

并且知道它有效

// Service guard
import {RouteGuard} from '@acn-collections-ws/shared';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    相关资源
    最近更新 更多