如何跨驻留在应用程序中的页面共享数据。谁能介绍一下 nativescript 中的 localstorage?
最佳答案
您的问题可以通过多种方式解读,因此很难给您一个好的答案,但我会尝试:
如果你想在导航时将数据从一个页面传递到另一个页面
创建带有上下文的导航条目
var navigationEntry = {
moduleName: "details-page",
context: {info: "something you want to pass to your page"},
animated: false
};
topmost.navigate(navigationEntry);
...在您要导航到的页面上,选择该上下文:
function onLoaded(args) {
console.log(args.object.navigationContext);
}
See documentation about Navigation
如果你想创建整个应用程序可用的数据
只需创建一个 singleton并请求它,就像在任何其他 Javascript 应用程序中一样。
例如
文件:myData.js
var data = {
something: 'a value here',
somethingElse: 1
somethingMany: ['a', 'b', 'c']
};
exports.data = data;
在您想要读取该数据的任何文件中:
var data = require("./myData.js").data;
console.log(data);
Read more about modules in Javascript
如果想在本地设备上持久化数据
如果你想写入和读取数据,以便你可以在 session 之间保存它:
对于非复杂数据,使用application-settings
。例如
var appSettings = require("application-settings");
appSettings.setString("stringKey", "String value"); // Writing
var value = appSettings.getString("stringKey", "No string value"); // Reading
// will return "No string value" if there is no value for "stringKey"
console.log(value)
Read the docs about application-settings
您还可以使用 file-system
模块写入文件到设备,例如
var documents = fs.knownFolders.documents();
var path = fs.path.join(documents.path, "FileFromPath.txt");
var file = fs.File.fromPath(path);
// Writing text to the file.
file.writeText("Something")
.then(function () {
// Succeeded writing to the file.
}, function (error) {
// Failed to write to the file.
});
阅读关于 file-system 的文档
对于数据库,您可以使用一些模块,例如 nativescript-sqlite和 nativescript-couchbase
关于javascript - nativescript 中有 localstorage 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39463157/