如何动态设置angular路由?

How to set up dynamic on the fly angular routing?

我尝试通过以下两种方式在根组件 ngOnInit 中动态创建路由 app.component.ts

this.router.resetConfig([
  { path: 'news/:article-slug', component: ArticleComponent },
  { path: 'pages/:page', component: StaticPagesComponent },
  ...this.router.config
]);

this.route.config.unshift(
  { path: 'news/:article-slug', component: ArticleComponent },
  { path: 'pages/:page', component: StaticPagesComponent }
);

但是当我在浏览器中输入 URL 时,这两种方法都不起作用。它们仅在 URL 由 routerLink 生成并且我单击它们时才有效。

如何生成可以通过在浏览器中输入 URL 来访问的动态路由?

您必须将代码放在 app.component 构造函数中,而不是将代码放在 ngOnInit 中。

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private router: Router) {
    this.router.config.unshift(
      { path: 'page1', component: Page1Component },
      { path: 'page2', component: Page2Component }
    );
  }
}

此致