如何在页面刷新时保持预期的路线信息?

时间:2019-10-24 21:42:11

标签: angular angular-routing angular-oauth2-oidc

我们有一个Angular6前端,它使用angular-oauth2-oiudc包进行身份验证。该程序包仅允许来自auth服务器的一个重定向URL,这是一个问题,因为我们需要允许在应用程序中使用多个入口点(即,单击通过电子邮件发送的链接到特定页面,因此我们要使用哈希定位) )。因此,我们已禁用了应用程序路由模块中的初始导航功能,以便进行更多控制:

imports: [RouterModule.forRoot(ROUTES, {useHash: true, initialNavigation: false})],

我们正在app.component.ts ngOnInit方法中进行简单登录。我遵循了其他解决方案,以邀请事件侦听器捕获路由器事件并捕获URL。这适用于初始导航到应用程序,但是当您刷新浏览器或通过链接转到特定页面时,不适用于停留在同一页面上。对于这些情况,我不知道从app.component调用路线网址的方法,有人做过这样的事情吗?

app.component:

export class AppComponent implements OnInit, AfterViewInit {

  currentUrl: string = null;
  ...

  constructor(
    storageManager: LocalStoreManager,
    private toastaService: ToastaService,
    private toastaConfig: ToastaConfig,
    private notificationService: NotificationService,
    private appTitleService: AppTitleService,
    private translationService: AppTranslationService,
    public configurations: ConfigurationService,
    public router: Router,
    private route: ActivatedRoute,
    @Inject(PLATFORM_ID) private platformId: Object,
        private oauthService: OAuthService) {

    if (isPlatformBrowser(this.platformId)) {
      this.oauthService.configure(environment.authconfig);
      this.oauthService.tokenValidationHandler = new JwksValidationHandler();
    }
    //route event listener
    this.router.events.subscribe((event: Event) => {
      if (event instanceof NavigationEnd) {
          console.log('URL: ', event.url);
          this.currentUrl = event.url;
      }
    });

    ...
  }

...


  ngOnInit() {//login and redirect logic here

    if (isPlatformBrowser(this.platformId)) {

        this.oauthService.loadDiscoveryDocumentAndTryLogin().then(_ => {
          if (
              !this.oauthService.hasValidIdToken() ||
              !this.oauthService.hasValidAccessToken()
              ) {
              this.oauthService.initImplicitFlow();
          }
          else {
            this.oauthService.loadUserProfile().then((userInfo: any) => {
              const roles = userInfo.role;
            });
          }
          this.isUserLoggedIn = this.oauthService.hasValidIdToken() && this.oauthService.hasValidAccessToken();
          if(this.currentUrl){
            this.router.navigate([this.currentUrl]);
          } else {
            this.router.navigate(['/']);
          }

      });
    }

app-routing.module.ts可用的路由:

const routes: Routes = [
  { path: '', component: HomeComponent, data: { title: 'Home' } },
  { path: 'edit', component: EditComponent, data: { title: 'Edit' } },
  { path: 'home', redirectTo: '', pathMatch: 'full' },
  { path: '**', component: NotFoundComponent, data: { title: 'Page Not Found' } }
];

身份验证配置:

authconfig: {
  // Url of the Identity Provider
  issuer: '[Our Identity Server]',
  requireHttps: true,
  // URL of the SPA to redirect the user to after login
  redirectUri: 'http://localhost:4200/'
}

0 个答案:

没有答案