可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I want to pass data between two controllers (in addition to routing parameters) and I would like to know the correct way to do this.
For example: when I navigate to pattern /order/{id}
, I do this in the view controller:
this.getRouter().navTo("order", { id: sOrderId });
I want to pass additional JSON object which I don't want to be part of routing parameter.
What should I do in this case?
--edit
Wanted to add what I like to achieve with this
I want pass data from master to detail. Both master and detail page has individual routing patterns assigned. So user can land on master or detail directly. When they land on master - user can choose bunch of detail items, and navigate to first detail item, and from there navigate to other items he/she selected earlier on master. So what I want to pass is this selection from master controller to detail controller.
回答1:
Using Client-side Model
Usually, data are stored separately in models instead of assigned to local variables and passing them around. Model data can be then shared with anything that can access the model (e.g. View for data binding). Here is an example with a client-side JSONModel:
Create a client-side JSONModel which is set on a parent ManagedObject. E.g. on Component via manifest.json:
"sap.ui5": { "models": { "myModel": { "type": "sap.ui.model.json.JSONModel" } } }
In controller A, set the object to pass before navigating:
var dataToPass = /*...*/ this.getOwnerComponent().getModel("myModel").setProperty("/data", dataToPass);
In controller B, do something with the passed data. E.g. on patternMatched
handler:
onInit: function() { var orderRoute = this.getOwnerComponent().getRouter().getRoute("order"); orderRoute.attachPatternMatched(this.onPatternMatched, this); }, onPatternMatched: function() { /*Do sth with*/ this.getOwnerComponent().getModel("myModel").getProperty("/data"); },
Using NavContainer(Child) Events
There are several navigation-related events such as navigate
, BeforeHide
, BeforeShow
, etc. which contain both views - the source view (from
) and the target view (to
).
You can make use of the API data
to pass the data. Here is an example:
In controller A
onInit: function() { this.getView().addEventDelegate({ onBeforeHide: function(event) { var targetView = event.to; var dataToPass = /*...*/ targetView.data("data", dataToPass); } }, this); },
In controller B
onInit: function() { this.getView().addEventDelegate({ onBeforeShow: function(event) { /*Do sth with*/ this.getView().data("data"); } }, this); },
回答2:
You can create a local model (usually a JSONModel) and set it to inside your app Component.
// inside Component.js var model = new sap.ui.model.json.JSONModel({ foo: “bar”}); this.setModel(model);
Inside each controller you can use
var model = this.getOwnerComponent().getModel(); console.log(model.getProperty(“/foo”));