Angular4 - 在后卫

时间:2017-08-28 14:30:41

标签: angular angular2-modules angular2-guards

我有一个带有root和子组件的延迟加载模块。我还有一个服务来在根和子组件和兄弟之间共享数据。

后面的用例是一个向导,用户可以通过多个步骤设置一些数据。每个步骤的数据全局存储在服务中,以便父级和每个子组件都能够访问整个数据。

现在我想为单个步骤创建警卫,这应该检查之前的步骤是否已完成(服务中的数据已设置),以防止用户通过URL访问其他步骤而不执行上述步骤。

模块

@NgModule({
imports: [
    CommonModule,
    FormsModule,
    AppointmentAgreementRouting
],
declarations: [
    AppointmentAgreementComponent,
    TopicSectionComponent,
    BranchSectionComponent,
    DatetimeSectionComponent,
    PersonalDataSectionComponent,
    ConfirmationSectionComponent,
    SectionDirective
],
providers: [
    CanActivateBranch, <-- Guard which should check if the data is set in service
    { provide: 'components', useValue: [AppointmentAgreementComponent], multi: true }
],
entryComponents: [
    AppointmentAgreementComponent,
    TopicSectionComponent,
    BranchSectionComponent,
    DatetimeSectionComponent,
    PersonalDataSectionComponent,
    ConfirmationSectionComponent
]
})

路由

const appointmentAgreementRoutes: Routes = [{
path: '',
children: [
    {path: '', redirectTo: 'thema', pathMatch: 'full'},
    {path: 'thema', component: TopicSectionComponent},
    {path: 'filiale', component: BranchSectionComponent, canActivate: [CanActivateBranch]},
    {path: 'termin', component: DatetimeSectionComponent},
    {path: 'daten', component: PersonalDataSectionComponent},
    {path: 'bestaetigung', component: ConfirmationSectionComponent},
]
}];

根组分

@Component({
selector: 'appointment-agreement',
templateUrl: './appointmentAgreement.component.html',
providers: [
    AppointmentAgreementCommunicationService <-- Service to share data
]
})

我现在的问题是,我在根组件中提供服务,因为我需要为每个组件(root和childs)提供相同的服务实例。

但是我需要在模块中提供警卫,否则我得到“没有为CanActivateBranch(警卫)找到提供者”

如果我现在要将服务注入到防护中,我将获得“无服务提供商”,因为该服务仅在组件中提供,而不是在模块中提供。

有人知道如何解决这个问题吗?

提前多多感谢。

0 个答案:

没有答案
相关问题