首页 文章

如何从Nativescript中的兄弟路由传递参数到子路由

提问于
浏览
0

我在我的应用程序中使用 <page-router-outlet> 作为主要插座 .

在其中一个.html页面中,我有几个导航按钮和一个 <router-outlet> ,因为我想将这些按钮的结果渲染到 <router-outlet> .

在路由级别,该页面具有子路由:

const groceryListRoutes: Routes = [
  {
    path: 'grocery-lists',
    component: GroceryListsComponent,
  },
  {
    path: 'grocery-list/:id',
    component: GroceryListComponent,
    children: [
      {
        path: '',
        component: GroceryListProductsComponent,
      },
      {
        path: 'product-categories',
        component: ProductCategoriesComponent,
      },
      {
        path: 'products',
        component: ProductsComponent,
      },
    ],
  },

从列出所有购物清单的页面,我链接到使用 [nsRouterLink] 显示特定购物清单信息的页面,如下所示:

<Label [text]="item.name" margin="10" [nsRouterLink]="['/grocery-list', groceryListId]"></Label>

在那里我传递参数没有问题 . 一旦进入grocery-list /:id路由,它就会加载''子路由并在 <router-outlet> 中加载GroceryListProductsComponent .

现在我想在GroceryListProductsComponent HTML中使用此指令将GroceryListProductsComponent(在 <router-outlet> 中加载)链接到其他子路径(ProductsComponent):

<Label text="Next" width="80" height="80" [nsRouterLink]="['../products/', {zzz: 22}]"></Label>

该应用程序导航到兄弟路线但没有通过参数zzz . 我尝试过使用这样的查询参数:

<Label text="Next" width="80" height="80" [nsRouterLink]="['../products/', 22]"></Label>

并改变路线:

{
    path: 'products/:zzz',
    component: ProductsComponent,
}

没有结果 .

我正在获取目标组件上的参数,如下所示:

constructor(private pageRoute: PageRoute, private router: Router){
    this.pageRoute.activatedRoute
    .switchMap(activatedRoute => activatedRoute.params)
    .forEach((params) => { 
        this.zzz= params['zzz'];
    });
}

但是当我尝试警告()变量this.zzz时,它说:undefined .

ngOnInit(){
alert(this.zzz);
}

所以我的问题是,如何从Nativescript中的兄弟路由传递参数到子路由?因为当我在2根路径之间传递参数时我没有问题 .

提前致谢 .

1 回答

  • 0

    解决了这个问题 .

    我应该从PageRoute获得的activatedRoute访问子路由 . 所以构造函数应该是这样的:

    constructor(private pageRoute: PageRoute, private router: Router){
        this.pageRoute.activatedRoute
        .switchMap(activatedRoute => activatedRoute.children[0].paramMap)
        .forEach((params) => { 
            this.zzz= params['params']['zzz'];
        });
    }
    

    我使用以下方法从子路径访问参数:

    activatedRoute.children[0].paramMap
    

相关问题