带参数的路由不起作用

问题描述 投票:0回答:2

我正在遵循此处的教程,但我在使用参数进行路由时遇到了困难。

示例应用程序未在我的本地使用中运行,因此我将其更改为使用本地数据。但是,当我单击发票列表中的元素时,出现错误“未捕获错误:段“{invoicePath}”的值“Invoices/1”无效”。它应该打开一个新的详细信息页面并显示产品名称和金额。

这是我的路由清单:

"routing": {
      "config": {
        "routerClass": "sap.m.routing.Router",
        "viewType": "XML",
        "viewPath": "sap.ui.demo.wt.view",
        "controlId": "app",
        "controlAggregation": "pages"
      },
      "routes": [
        {
          "pattern": "",
          "name": "overview",
          "target": "overview"
        },
        {
          "pattern": "detail/{invoicePath}",
          "name": "detail",
          "target": "detail"
        }
      ],
      "targets": {
        "overview": {
          "viewName": "Overview"
        },
        "detail": {
          "viewName": "Detail"
        }
      }
    }

Invoices.json 示例数据:

{
  "Invoices": [
    {
      "ProductName": "Pineapple",
      "Quantity": 21,
      "ExtendedPrice": 87.2000,
      "ShipperName": "Fun Inc.",
      "ShippedDate": "2015-04-01T00:00:00",
      "Status": "A"
    }
  ]
}

InvoiceList.controller.js。我在其中填充发票列表并调用视图更改。

sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/ui/model/json/JSONModel",
    "sap/ui/demo/wt/model/formatter",
    "sap/ui/model/Filter",
    "sap/ui/model/FilterOperator"
], function (Controller, JSONModel, formatter, Filter, FilterOperator) {
    "use strict";

    return Controller.extend("sap.ui.demo.wt.controller.InvoiceList", {

        onPress: function (oEvent) {
            var oItem = oEvent.getSource();
            var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
            oRouter.navTo("detail", {
                invoicePath: oItem.getBindingContext("invoice").getPath().substr(1)
            });
        }
    });

});
sapui5
2个回答
6
投票

错误消息是由路由器库引发的。路由定义为

detail/{invoicePath}
并且您将
Invoice/1
作为参数传递,这是不允许的,因为参数包含被视为 URL 分段分隔符的斜杠。

但是,您提到您无法在本地运行该示例并进行了一些采用。该路径看起来像您现在正在使用 JSONModel。这意味着您还需要在示例中采用多个部分。

发票列表控制器:

oItem.getBindingContext("invoice").getPath().substr(10)

绑定上下文应该是

/Invoices/1
并且您只想传递唯一的索引。因此你需要切断
/Invoices/

详细控制器:

_onObjectMatched: function (oEvent) {
    this.getView().bindElement({
        path: "/Invoices/"+ oEvent.getParameter("arguments").invoicePath,
        model: "invoice"
    });
}

这会将您的视图绑定到相应模型中的

/Invoices/1


1
投票

@matbtt 的答案是正确的。

另一个解决方案是扩展 PATH。不需要

substr
,需要特殊的
offset

encodeURIComponent(oItem.getBindingContext("invoice").getPath())

_onObjectMatched: function (oEvent) {
    this.getView().bindElement({
        path: decodeURIComponent(oEvent.getParameter("arguments").invoicePath),
        model: "invoice"
    });
}

JSON 模型和 OData 都可以很好地工作。

© www.soinside.com 2019 - 2024. All rights reserved.