如何将任意(非参数化)数据传递到 Angular 中的路由?

How to pass arbitrary (non parameterized) data to a route in Angular?

首先:这不是骗局。链接的 dup 问题的答案使用了我不喜欢的服务。

我有一个路由 table :

const routes: Routes = [
  ...
  { path: 'comp1', loadChildren: './module1/module1.module.ts#Module1Module' },
  ...
  ];

在主要组件的 ctor (app.component.ts) 中,我导航到:

constructor(private router: Router){
  router.navigate(['/comp1',{aaa:222,bbb:{ccc:3}}])
}

但是 - 它被序列化为 URL。

https://angular-iqfnre-router.stackblitz.io/comp1;aaa=222;bbb=%5Bobject%20Object%5D

现在 - 我不希望它出现在 url 中。 (更不用说该值无效)

此外 - 惰性模块中的远程路由是:

const routes: Routes = [
  {
    path: '', component: Comp1Component,

    children: [{
      path: 'acomp', component: AComponent,
    }]

  }
];

所以它不支持参数(我说的不是参数而是复杂的数据)。

我不想改变路线table。

问题:

如何将任意(复杂)数据传递给路由 - 路由后如何读取它?

Stackblitz

NB

我不想使用服务。我确定还有另一种选择可以用数据加载路线。 docs提到了NavigationExtras,但我认为它仍然使用URL。 (请不要字符串化)。

对于这种要求,我建议使用共享服务。这样您就可以传递所需的数据类型,而不会在路由上造成任何额外开销。

还没有机会对此进行全面测试,但似乎可以在一条简单的路线上工作 虽然目前它 stringify 不是最好的对象。

在全局 component/service 添加

let routeData = null;
    this.router.events
          .filter((event) => (event instanceof ActivationStart || event instanceof ActivationEnd)).subscribe((event) => {

            if (event instanceof ActivationStart) {
              if(event.snapshot.params) {
                let routeDataStr:string = event.snapshot.params.routeData;

                if (routeDataStr) {
                  routeData = JSON.parse(routeDataStr);
                  if (event.snapshot.url[0]) {
                    this.router.navigate([event.snapshot.url[0].path]);
                  }
                }
              }
            } else if (event instanceof ActivationEnd) {

              let actEnd:ActivationEnd = event;

              if (routeData) {
                actEnd.snapshot.data = actEnd.snapshot.data == null ? {} : actEnd.snapshot.data;
                actEnd.snapshot.data.routeData = routeData
              }
            }
          })

然后触发导航使用

let dataob:DataObject = {
  blah: 123
}
this.router.navigate(['/comp1', {routeData: JSON.stringify(dataob)}]);

在您刚刚导航到的组件上,您现在可以访问 activeRoute 上的数据

  constructor(private route: ActivatedRoute, private router: Router) { }

  ngOnInit() {
    console.log(this.route.snapshot.data.routeData)
  }

请参阅 https://yakovfain.com/2015/11/11/angular-2-passing-data-to-routes 中的 "Passing static data to a route" 部分:

Passing static data to a route

While most of the times parent components will be passing data to their children, Angular also offers a mechanism to pass additional data to components at the time of the route configuration. For example, besides the dynamic data like product ID we may need to pass a flag indicating if the application runs in production environment or not. This can be done by using the data property of your route configuration. For example, our route for the product details can be configured as follows:

{path: 'product/:id', component: ProductDetailComponentParam ,
                      data: [{isProd: true}]}

The data property can contain an array of arbitrary string key-values pairs. When the router will open ProductDetailComponentParam the data value will be located in the data property of the ActivatedRoute.snapshot:

export class ProductDetailComponentParam {
  productID: string;
  isProdEnvironment: string;

  constructor(route: ActivatedRoute) {
    this.productID = route.snapshot.params['id'];

    this.isProdEnvironment = route.snapshot.data[0]['isProd'];
  }
}

Passing data to a route via the data property is not an alternative to configuring parameters in the path property as in path: ‘product/:id’ but can come handy when you need to pass some data to a route during the configuration phase, e.g. is it a production or QA environment.