I am using angular-translate with LocalStorage and it works very well. Locales are cached or stored on local disk. When the browser is closed and re-launched the chosen locale is persisted.
My question is how can I access that cached or stored locale that's on disk in one of my controllers? To better explain here's the workflow that is not working:
1. Launch browser to localhost and can see the site with previously chosen locale
2. Attempt to access the current locale from either the
2.1 $translate.proposedLanguage()
2.2 tmhDynamicLocale
3. Both are undefined -- even though the correct language is shown
4. Select language choice once more
5. current locale from both the above is now correct
Here is the JSFiddle for the module and locale service. Not runnable code. Just an example of the code I'm using
I am trying to access currentLocale but it is undefined until the user makes a selection (again). I know it's stored somewhere since the original selection is persisted after browser exit.
After about 2 hours in a rabbit whole of API docs and angular-translate-* sources files I found that I can pass $translateLocalStorage to my controller and then call $translateLocalStorage.get() which will return that cached localId.
That method pulls the localId from `$window.localStorage.getItem. That code is
get: function (name) {
if(!langKey) {
langKey = $window.localStorage.getItem(name);
}
return langKey;
}
So all you would need to do is:
angular.module('myModule')
.controller('QueryController', function($scope, es, $translateLocalStorage) {
$scope.show_results = function(results) {
var currentLocale = $translateLocalStorgae.get();
}
});
Related
I've been trying to use
Office.context.roamingSettings.set("keyVal", value)
Office.context.roamingSettings.get("keyVal")
To save in storage, but it only work for the current session.
Now I've been trying to the saveAsync. But it doesn't take parameters. So I wanna how it supposed to be used. And also if it keeps the data in all platforms for the user(OWA, mobile, and Desktop)
Office.context.roamingSettings.saveAsync(function (result) {
if (result.status !== Office.AsyncResultStatus.Succeeded) {
console.error(`Action failed with message ${result.error.message}`);
} else {
console.log(`Settings saved with status: ${result.status}`);
}
});
During the lifetime of the session you can just use the set and get methods to work with the in-memory copy of the settings property bag.
When you want to persist the settings so that they are available the next time the add-in is used, use the saveAsync method to save the settings after calling the set method. For an example see this code snippet: https://github.com/OfficeDev/office-js-snippets/blob/main/samples/outlook/10-roaming-settings/roaming-settings.yaml
I am developing a firefox addon. i use localStorage to save some data and retrieve.
function to check if it is available or not
if(!localStorage.getItem('font')) {
populateStorage();
}else{
var aValue = localStorage.getItem('font');
alert(aValue);
if not then create
function populateStorage(){
localStorage.setItem('cname', name);
localStorage.setItem('font', 'Helvetica');
localStorage.setItem('image', 'myCat.png');
}
This is perfectly working localhost but if i visit other host like google.com and try to get i am getting error not found
if(!localStorage.getItem('font')) {
alert('Not found !!!!');
}else{
var aValue = localStorage.getItem('font');
alert(aValue);
}
is there any way to fix this issue ? or am i doing it in wrong way ?
LocalStorage is intended to be accessible only from the same host. This allows different websites to have a different scope for their data, and also ensures that one website cannot access data from another website.
From MDN,
The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions.
From: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
If you need to share data across different domains, you should use server-side persistence.
From what I've undestood local storage is not cross domain solution, so this behavior is correct.
What you need to do is fallow MDN solution. I've found something like this:
// define 2 objects
var monster = {
name: "Kraken",
tentacles: true,
eyeCount: 10
}
var kitten = {
name: "Moggy",
tentacles: false,
eyeCount: 2
}
// store the objects
browser.storage.local.set({kitten, monster})
.then(setItem, onError);
(code copied from MDN > JavaScript APIs > storage )
In this solution data will be pinned to browser/extension, not to domain. But be aware, that data still will be destroyed when user clear browser cache or something like that.
RingCentral JavaScript SDK handle redirect URI point to local JavaScript function
As-per Doc, they give option
RingCentral.SDK.handleLoginRedirect()
but dont know how to use that
var SDK = require('ringcentral');
rcsdk = new SDK({
server: SDK.server.sandbox,
appKey: '_app_key',
appSecret: 'app_password',
redirectUri: ''
})
function handleredirectURI(){
//handle redirections
}
We need points out our handleredirectURI function
Thanks in advance
Per the documentation. The context is 3-legged oAuth. Here is a demo: https://github.com/ringcentral/ringcentral-demos-oauth/tree/master/javascript
However the demo doesn't use the handleredirectURI method. Which means that the method is simply an utility method and it's not required to use it.
For the usage of handleredirectURI, I will come back and update my answer later.
Update
Here is the source code for handleredirectURI: https://github.com/ringcentral/ringcentral-js/blob/669b7d06254d3620c5a5f24c94b401aa862be948/src/SDK.js#L115-L124
You can see that the method parses win.location to get some useful data and postMessage back to its opener.
Unit tests for handleredirectURI: https://github.com/ringcentral/ringcentral-js/blob/669b7d06254d3620c5a5f24c94b401aa862be948/src/SDK-spec.js#L27-L63
Update 2
I read handleredirectURI' source code, unit tests, sample code again and I think its usage is just like what is written in its documentation:
Popup Setup
This setup is good when your app is rendered as a widget on a third-party sites.
If you would like to simply open RingCentral login pages in a popup, you may use the following short-hand in your app's login page:
var platform = rcsdk.platform();
var loginUrl = platform.loginUrl({implicit: true}); // implicit parameter is optional, default false
platform
.loginWindow({url: loginUrl}) // this method also allows to supply more options to control window position
.then(function (loginOptions){
return platform.login(loginOptions);
})
.then(...)
.catch(...);
In this case your landing page (the one to which Redirect URI points) need to call the following code:
RingCentral.SDK.handleLoginRedirect();
Explained:
Run the first code snippet to open the login popup.
In the redirected to page, run the second code snippet (that one line of code) to get everything else done.
After that the authorization part is done and you can invoke other APIs.
Let me know if you have more questions.
I'm creating a Windows 8 App (using HTML 5 and JavaScript) for someone and they've changed up the requirements on me as far as data storage and I could use some guidance. What I need is a data source that will persist only for the local user and not be online in a database or in the cloud. The users will be assigned a tablet with the app installed and they will enter data via forms to customize their local copy.
Here's my requirements:
-Data MUST persist through the lifetime that the app is installed on the device.
-I need to be able to query the data to some degree. I've basically got about 15-20 forms that will accept input data and then a main form that will feed off those 15-20 "sub" forms to populate drop-down and selection options.
-Size should not be an issue, it's all text data and not much of it will be entered. Can't see this going more than a couple hundred MBs over the lifetime of the app.
I've looked into XML, indexedDB (sounds good on the outside, but haven't found any kind of guarantee this will persist), and Application Data (local) which seems extremely limited in my reading capabilities.
What do you think my best bet is? Any advice would be greatly appreciated.
Thanks.
This should help
(function () {
"use strict";
var page = WinJS.UI.Pages.define("/html/index.html", {
ready: function (element, options) {
//do your things
}
});
var roamingFolder = Windows.Storage.ApplicationData.current.roamingFolder;
var afile = "FileToStoreStuff.txt";
function makefile() {
roamingFolder.createFileAsync(afile, Windows.Storage.CreationCollisionOption.replaceExisting)
.then(function (file) {
return Windows.Storage.FileIO.writeTextAsync(file);
})
}
function fileRead() {
roamingFolder.getFileAsync(filename)
.then(function (file) {
return Windows.Storage.FileIO.readTextAsync(file);
}).done(function (text) {
//do stuff
);
}
})();
This kind of assumes that your data may change. If it doesn't you can adapt a different approach, for instance replacing the roamingFolder variable with something like:
var localSettings = applicationData.localSettings;
var localFolder = applicationData.localFolder;
Take a look at the dev docs if you need to access data from within the app elsewhere.
My application receives data from the another server, using API with limited number of requests. Data changing rarely, but may be necessary even after refresh page.
What's the best solution this problem, using cookie or HTML5
WebStorage?
And may be have other way to solve this task?
As much as cross browser compatibility matters, cookie is the only choice rather than web storage.
But the question really depends on what kind of data you are caching?
For what you are trying, cookie and web-storage might not be needed at all.
Cookies are used to store configuration related information, rather than actual data itself.
Web storage supports persistent data storage, similar to cookies but with a greatly enhanced capacity and no information stored in the HTTP request header. [1]
I would rather say, it would be stupid to cache the entire page as cookie or web-storage both. For these purposes, server-side caching options might be the better way.
Update:
Quoting:
data about user activity in some social networks (fb, vk, google+)
Detect the web-storage features, using libraries like mordernizr and if does not exists fall back to cookie method. A simple example
if (Modernizr.localstorage) {
// browser supports local storage
// Use this method
} else {
// browser doesn't support local storage
// Use Cookie Method
}
[1]: http://en.wikipedia.org/wiki/Web_storage
I wrote this lib to solve the same problem:
Cache your data with Javascript using cacheJS
Here are some basic usages
// just add new cache using array as key
cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:1,type:'json'}, jsonData);
// remove cache using key
cacheJS.removeByKey({blogId:1,type:'json'});
// add cache with ttl and contextual key
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', 3600, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd'});
// remove cache with con textual key
// cache for blog 2 and 3 will be removed
cacheJS.removeByContext({author:'hoangnd'})
Here is an example of caching data from JQuery AJAX. So if you only want to make the call when you don't have the data yet, its really simple. just do this (example). Here we first check if we have the load information (keyed on line, location and shipdate), and only if we dont, we make the AJAX call and put that data into our cache:
var dict = [];
function checkCachedLoadLine(line, location, shipDate, callback) {
var ret = 0;
if(!((line+location+shipDate) in dict)) {
productionLineService.getProductionLoadLine(line, location, shipDate, callback);
}
return dict[line+location+shipDate];
}
...then in the call back write the value to the cache
function callback(data) {
if (!data) {
document.getElementById('htmlid').innerHTML = 'N/A';
} else {
document.getElementById('htmlid').innerHTML = data[0];
dict[data[2]+data[3]+data[4]] = data[0];
}
}