使用配置中的外部 URL 填充路由

Populate a route with an external URL from config

我的路线定义为:

export const routes: Routes = [
  { path: "", redirectTo: "/datasets", pathMatch: "full" },
  {
  path: "help/youtube",
  canActivate: [RedirectGuard],
  component: RedirectGuard,
  data: {
    externalUrl:  "https://youtube.com"
  }
},
...
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule {}

其中redirect guard是一个处理外部URLs的模块。

我需要从我的 appConfig 中获取它,而不是硬编码 externalUrl,但是如果没有像这样的构造函数,我就无法访问 appConfig:

constructor(@Inject(APP_CONFIG) private appConfig) {}

因为 appConfig 被设置为带有注入令牌的模块,例如:

export const APP_CONFIG = new InjectionToken<AppConfig>("app.config");

所以我尝试将此注入添加到我的 AppRoutingModule 但没有成功。

如何访问 appConfig 来填充此外部 URL?

所以我找到了解决办法。

从我的 redirect-guard(我从 here 中获取)

访问 appConfig
@Injectable()
export class RedirectGuard implements CanActivate {

  constructor(private router: Router, @Inject(APP_CONFIG) public appConfig: AppConfig) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {


      window.location.href = this.appConfig[route.data["externalUrl"]];
      return true;

  }
}

将配置项名称作为 data["externalUrl"] 传递,我将很快将其重命名为更合适的名称。这意味着硬编码 URL 将无法工作,但我可以接受。

app-routing.module 中的路由定义如下所示:

{
    path: "help/ingestManual",
    canActivate: [RedirectGuard],
    component: RedirectGuard,
    data: {
      externalUrl:  "ingestManual"
    }
  }

其中 ingestManual 是我的配置文件中定义的项目。

这使我能够将应用程序路由重定向到外部 URL。