使用来自数据库的单个或多个参数构建动态路由

时间:2018-04-23 15:01:20

标签: angular typescript angular-routing angular-router

以下是links.json:

[
  {
    "id": "1",
    "name": "Basic Item Definition",
    "routerLink": "/itemmaint/basicitemdefinition",
    "param1": "35",
    "param2": "",
    "parentId": " 0"
  },
  {
    "id": "2",
    "name": "General Product Attributes",
    "routerLink": "/itemmaint/generalproductattributes",
    "param1": "35",
    "param2": "edit",
    "parentId": " 0"
  },
  {
    "id": "3",
    "name": "Shipper Item Composition",
    "routerLink": "/itemmaint/shipperitem",
    "param1": "35",
    "param2": "",
    "parentId": " 0"
  }
]

以上链接来自数据库,有些链接有两个参数,有些参数有一个参数:

  <mat-list-item *ngFor="let lnkObj of itemSummarylinks" class="app-sidenav-content">
      <a [routerLink]="buildDynamicRoutes(lnkObj)">
                        {{link.name}}
      </a>
  </mat-list-item>

在组件中:

buildDynamicRoutes(lnkObj)
{
  //how to build the dynamic routes here based on the params
  //if its single param then route should be /itemmaint/basicitemdefinition/35
  //if its double param it should be /itemmaint/basicitemdefinition/35/edit
}
路线中的

 { path: 'basicitemdefinition:id', component: BasicItemDefinitionDetailComponent },
  { path: 'generalproductattributes:id:edit', component: GeneralProductAttributesDetailComponent }

在使用动态参数构建动态路由时,我无法进行字符串插值,所以尝试这种方法。

1 个答案:

答案 0 :(得分:0)

这取决于你是想完全抽象出来还是只使用param1 / param2。在param1 / param2的情况下,我会做这样的事情:

if (lnkObj.param2){
        //do the logic if there is a param 2
    } else {
        //do the logic for other cases
    }

// this can be simplified into:
return linkObj.param2 ? '/itemmaint/basicitemdefinition/35/edit' : '/itemmaint/basicitemdefinition/35';

如果您想要将其抽象出来,因为您可能希望将来包含其他参数,我会创建params数组,然后只检查该数组的长度,您就会知道有多少参数。

const arr = ['param1', 'param2']
const lengthOfArray = arr.length()
// lengthOfArray will be 2 so you know you have two params and then do the logic

希望这会对你有所帮助。

相关问题