首页 > 解决方案 > 如何从外部访问组件模型

问题描述

我在index.html中创建了一个 shell-in-shell 构造:

sap.ui.getCore().attachInit(function () {
     // create a new Shell that contains the root view
     var oShell = new sap.m.Shell({
         id: "appShell",
         app: new sap.ui.core.ComponentContainer({
             name: "internal_app",
             height: "100%"
         })
    });

    // load the view that contains the unified shell
    var oAppShellView = sap.ui.view({
        type: sap.ui.core.mvc.ViewType.XML,
        viewName: "internal_app.view.AppShell"
    });
    // access the unified shell from the view
    var oUnifiedShell = oAppShellView.byId("unifiedShell");
    // place the app shell in the unified shell
    oUnifiedShell.addContent(oShell);
    oAppShellView.placeAt("content");
});

此外,manifest.json 中还定义了一个默认模型:

....
},
"models": {
  "": {
    "type": "sap.ui.model.json.JSONModel"
  }
},
....

在视图的控制器internal_app.view.AppShell(由上面的代码片段创建)中,我现在想访问默认模型,但也this.getModel()没有this.getOwnerComponent().getModel()getModel()getOwnerComponent()return undefined)工作。我假设 AppShell 控制器没有所有者。但是如何访问该onInit控制器的默认模型?

标签: sapui5

解决方案


您的案例中的应用程序结构有些不寻常 - 不过,您始终可以访问 manifest.json 中定义的模型,只要您可以访问内部组件。

假设this正在引用 的控制器internal_app.view.AppShell,您可以像这样获得默认模型:

onInit: function() {
  var innerShell = sap.ui.getCore().byId("appShell"); // only if the app is standalone
  this.componentLoaded(innerShell.getApp()).then(this.onComponentCreated.bind(this));
},

componentLoaded: function(componentContainer) {
  var component = componentContainer.getComponent();
  return component ? Promise.resolve(component) : new Promise(function(resolve) {
    componentContainer.attachEventOnce("componentCreated", function(event) {
      resolve(event.getParameter("component"));
    }, this);
  }.bind(this));
},

onComponentCreated: function(component) {
  var myDefaultModel = component.getModel(); // model from manifest.json
  // ...
}

推荐阅读