【问题标题】:How to pass a parameter to child route from a sibling route in Nativescript如何将参数从 Nativescript 中的兄弟路由传递给子路由
【发布时间】:2018-05-12 06:35:31
【问题描述】:

我在我的应用程序中使用<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 路由,它就会加载''子路由并在&lt;router-outlet&gt; 中加载GroceryListProductsComponent。

现在我想在 GroceryListProductsComponent HTML 中使用此指令从 GroceryListProductsComponent(在 &lt;router-outlet&gt; 中加载)链接到另一个子路由(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'];
    });
}

但是当我尝试 alert() 变量 this.zzz 时,它说:未定义。

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

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

提前致谢。

【问题讨论】:

    标签: angular nativescript angular2-nativescript nativescript-angular


    【解决方案1】:

    解决了这个问题。

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

    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
    

    【讨论】:

      猜你喜欢
      • 2016-09-21
      • 1970-01-01
      • 2017-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-17
      • 2015-03-16
      • 2016-07-01
      相关资源
      最近更新 更多