Angular4 - use components service in guard

不羁岁月 提交于 2019-12-24 09:57:08

问题


I have a lazy-loaded-module with a root and child componets. I also have a service to share data between the root and the child components and siblings.

The use case behind is a wizard, where the user can set some data in multiple steps. The data of each step is stored globally in the service, so that the parent and every child component is able to access the whole data.

Now i want to create guards for the single steps, which should check if the step before was done (data in the service is set) to prevent the user from accessing further steps by URL without doing the steps before.

Module

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

Routing

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

Root-Component

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

My problem now is, that i am providing the service in the root component, because i need the same service instance for every of these components (root and childs).

But i need to provide the guard in the module, because otherwise i am getting "No provider found for CanActivateBranch (guard)"

If i want to inject the service now into the guard, i am getting "No provider for ...service" because the service is just provided in the component and not in the module.

Does anybody has an idea how to solve this problem?

Thanks a lot in advance.

来源:https://stackoverflow.com/questions/45921454/angular4-use-components-service-in-guard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!