gpt4 book ai didi

初始化前从 REST 服务的 Angular 加载路由

转载 作者:行者123 更新时间:2023-12-03 16:50:24 27 4
gpt4 key购买 nike

我正在研究 Angular 8 从 REST 服务动态创建路由的可能性。
这个想法是用户可以通过在网页上路由来创建应该可以访问的页面。

我已经看到了动态添加路由的选项,但是我想要路由 在应用程序的其余部分之前加载 ,以便当用户访问时: 'website/generatedPage' 路由在应用程序完全加载之前就位。

在应用程序继续路由选项之前,如何确保来自 REST 服务的路由就位?

以下代码将路由添加到后期:

    constructor(
private sitemapService: SitemapService,
private router: Router
) {
this.sitemapService.getSiteMap().then(result => {
result.forEach(sitemapItem => {
this.router.config.push({ path: sitemapItem.pageName, component: PageComponent });
});
});
}

使用此代码,您可以在加载应用程序时导航到该页面,但是,当您直接请求路由时,它尚未加载。

先感谢您!

最佳答案

好的,所以我遇到了完全相同的问题,当我偶然发现这三篇文章并使用它们的组合来提出解决方案时,我实际上打算使用您的“解决方案”。

引用文献:

https://long2know.com/2017/11/angular-dynamic-routes-and-application-initialization/
https://medium.com/codegg/pre-loading-user-specific-routes-in-angular-ce829430e1cb
https://www.tektutorialshub.com/angular/angular-how-to-use-app-initializer/#where-to-use-app-initializer

我的用例:我需要根据 GET 响应创建路由

以下是对我有用的内容:

1.首先,我新建了一个app-init服务:


import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

@Injectable()
export class AppInitService {

constructor(private Router: Router) {}

init() {
return new Promise<void>((resolve, reject) => {

// Simple example from an array. In reality, I used the response of
// a GET. Important thing is that the app will wait for this promise to resolve
const newDynamicRoutes = ['bulbasaur','charmander','squirtle']
const routes = this.Router.config;

newDynamicRoutes.forEach(routeName => {
routes.push({ path: routeName, component: <YourComponent> });
});

this.Router.resetConfig(routes);
resolve();
});
}
}

2.然后,我在app.module.ts中使用它与 APP_INITIALIZER

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppInitService } from './services/app-init/app-init.service'; // New service that I created

...

export function initializeApp(appInitService: AppInitService) {
return (): Promise<any> => {
return appInitService.init();
}
}

...

providers: [
AppInitService,
{
provide: APP_INITIALIZER,
useFactory: initializeApp,
multi: true,
deps: [AppInitService]
}
],
bootstrap: [AppComponent]
})
export class AppModule {}

这就像一个魅力。它让我可以根据 API 的响应创建路由。

关于初始化前从 REST 服务的 Angular 加载路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59236582/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com