Добавление Dynami c маршрутов в angular - PullRequest
1 голос
/ 28 апреля 2020

Я создал родительский и дочерний маршрут в приложении angular 8. Один из моих дочерних маршрутов, называемый соглашением, должен быть динамическим c. Это означает, что если есть три соглашения, должно быть три меню sidenav, показывающих маршрут к отдельной странице. Например, соглашение 1, соглашение 2, соглашение 3 et c. Я бы знал количество соглашений на момент загрузки компонента соглашений.

Как создать соглашение динамически. Как вы можете видеть сейчас, это stati c. Я также приложил снимок экрана, чтобы увидеть, как он выглядит.

снимок экрана

enter image description here

app.route

import { Routes } from '@angular/router';
import { NgxPermissionsGuard } from 'ngx-permissions';
import { MsalGuard } from '@azure/msal-angular';

import { SecurityPermissions } from './shared/constants/securityPermissions';
import { HomeGuard } from './shared/services/home.guard';

export const AppRoutes: Routes = [
  {
    path: '',
    loadChildren: './modules/client-home/client-home.module#ClientHomeModule',
    canActivate: [HomeGuard]
  },
  {
    path: 'client-home',
    loadChildren: './modules/client-home/client-home.module#ClientHomeModule',
    canActivate: [MsalGuard, NgxPermissionsGuard],
    data: {
      permissions: {
        only: [SecurityPermissions.organisation.AccessOrganisation]
      }
    }
  },
  {
    path: 'individual-business-application',
    loadChildren: './modules/iba/iba.module#IbaModule',
    canActivate: [MsalGuard, NgxPermissionsGuard],
    data: {
      permissions: {
        only: [
          SecurityPermissions.iba.CompleteIba,
          SecurityPermissions.iba.ViewIbaSummary
        ]
      }
    }
  },
  { path: '**', redirectTo: '/' }
];

iba child route

const ibaRoutes: Routes = [
  {
    path: '',
    canActivate: [IbaGuard],
    component: IbaComponent,
    resolve: { model: IbaResolve },
    children: [
      {
        path: '', redirectTo: 'summary'
      },
      {
        path: 'load/:clientRef',
        component: ContactComponent,
        data: { hidden: true }
      },
      {
        path: 'contact',
        component: ContactComponent,
        data: {
          title: '1. Contact',
          role: [SecurityPermissions.iba.CompleteIba],
          order: 1,
          sectionName: SectionNames.iba,
          baseAddress: 'individual-business-application',
          hidden: false
        }
      },
      {
        path: 'address',
        component: AddressComponent,
        data: {
          title: '2. Address',
          role: [SecurityPermissions.iba.CompleteIba],
          order: 2,
          sectionName: SectionNames.iba,
          baseAddress: 'individual-business-application',
          hidden: false
        }
      },
      {
        path: 'employment',
        component: EmploymentComponent,
        data: {
          title: '3. Employment',
          role: [SecurityPermissions.iba.CompleteIba],
          order: 3,
          sectionName: SectionNames.iba,
          baseAddress: 'individual-business-application',
          hidden: false
        }
      },
      {
        path: 'fitness',
        component: FitnessComponent,
        data: {
          title: '4. Fitness',
          role: [SecurityPermissions.iba.CompleteIba],
          order: 4,
          sectionName: SectionNames.iba,
          baseAddress: 'individual-business-application',
          hidden: false
        }
      },
      {
        path: 'identification-questions',
        component: IdentificationComponent,
        canActivate: [NgxPermissionsGuard],
        data: {
          title: '5. Identification',
          permissions: {
            only: [SecurityPermissions.iba.UploadIbaIdentification]
          },
          role: [SecurityPermissions.iba.UploadIbaIdentification],
          order: 5,
          sectionName: SectionNames.iba,
          baseAddress: 'individual-business-application',
          hidden: false
        }
      },
      {
        path: 'additional-information',
        component: AdditionalInformationComponent,
        canActivate: [NgxPermissionsGuard],
        data: {
          title: 'Additional Information',
          permissions: {
            only: [SecurityPermissions.iba.UploadIbaIdentification]
          },
          role: [SecurityPermissions.iba.UploadIbaIdentification],
          order: 6,
          sectionName: SectionNames.iba,
          baseAddress: 'individual-business-application',
          hidden: true
        }
      },
      {
        path: 'agreement',
        component: MultiAgreementComponent,
        data: {
          title: '6. Agreement',
          order: 7,
          sectionName: SectionNames.iba,
          baseAddress: 'individual-business-application',
          hidden: false
        }
      },
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(ibaRoutes)],
  exports: [RouterModule]
})
export class IbaRoutingModule {}

1 Ответ

1 голос
/ 28 апреля 2020

Я надеюсь, что я правильно понял ваш вопрос. Вот что вы можете сделать:

1. Храните соглашения в службе, как только вы их знаете:

yourService.agreements = [{ id: '1' }, { id: '2' }, { id: '3' }];

2. Создайте новую охрану, измените путь для соглашений на agreement/:agreement и добавьте canActivate[YourGuard]

...
    path: 'agreement/:agreement',
    canActivate: [YourGuard],
...

3. Реализуйте YourGuard

  1. Необходимо, чтобы пользователь не мог перейти к .../agreement/<agreement>, если <agreement> не существует
  2. Если вы найдете соглашение в своем классе обслуживания, вернуть true, если не вернуть false
  3. Обратите внимание, что я также добавил this.router.navigate(('' as unknown) as any[]), чтобы избежать перенаправления на пустую страницу. Это обходной путь для известной проблемы, которая, кажется, работает для меня. Я написал немного больше об этом здесь
export class YourGuard implements CanActivate {
    constructor(private yourService: YourService, private router: Router) {}

    canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
    ): boolean {
        const param = next.paramMap.get('agreement');
        if (!!this.yourService.agreements.find(a => a.id === param)) {
            return true;
        } else {
            this.router.navigate(('' as unknown) as any[]);
            return false;
        }
    }
}

4. Теперь вы можете получить соглашение в вашем компоненте

export class MultiAgreementComponent implements OnInit {
    agreement: { id: string };

    constructor(
        private activatedRoute: ActivatedRoute,
        private yourService: YourService
    ) {}

    ngOnInit(): void {
        const param = this.activatedRoute.snapshot.paramMap.get('agreement');
        this.agreement = this.yourService.agreements.find(a => a.id === param);
    }
}

5. Для того чтобы перечислить все ссылки на компоненты, вы можете просто использовать *ngFor

. Я собрал всего одну версию вашего приложения, чтобы проверить это, поэтому routerLink может отличаться:

<div *ngFor="let agreement of yourService.agreements">
  <a routerLink="agreement/{{ agreement.id }}">
    Agreement {{ agreement.id }}
  </a>
</div>

Надеюсь, этот ответ решил вашу проблему. Не стесняйтесь спрашивать, если что-то еще не ясно.

...