chrome.storage.sync.get未返回值-Angular服务
chrome.storage.sync.get not returning value - Angular services
我正在使用angular&尝试使用chrome.storage设置&获取随机生成的id,但在"获取"时没有获得该id,下面是我的代码:
angular.module('chromeExtension')
.service('customService', ['$window', '$timeout', function ($window, $timeout) {
this.getUniqueId = function() {
return chrome.storage.sync.get('unique_app_id', function(data) {
console.log(data.unique_app_id); // Here I am getting the id
if(data.unique_app_id) {
return data.unique_app_id;
} else {
uniqueId = Math.round((Math.pow(36, 20 + 1) - Math.random() * Math.pow(36, 20))).toString(36).slice(1);
chrome.storage.sync.set({'unique_app_id': uniqueId});
return uniqueId;
}
});
}
}]);
因此,当我在控制器中调用这个getUniqueId时,我得到了未定义,我还使用了超时思想,因为chrome.storage.sync是异步调用,所以这可能是原因,但运气不好。下面是我调用该函数的控制器:
angular.module('chromeExtension')
.controller('sampleController',['$scope', 'customService', function ($scope, customService) {
$scope.uniqueId = customService.getUniqueid();
console.log("Unique: ", $scope.uniqueId); // this is giving me undefined or null
}]);
chrome.storage.sync.get
是一个异步调用,不能直接得到结果。
一种解决方法是添加回调并在回调中调用console.log
,我不熟悉angular.js
,但示例代码是:
angular.module('chromeExtension')
.service('customService', ['$window', '$timeout', function ($window, $timeout) {
this.getUniqueId = function(callback) {
return chrome.storage.sync.get('unique_app_id', function(data) {
console.log(data.unique_app_id); // Here I am getting the id
if(data.unique_app_id) {
callback(data.unique_app_id);
} else {
uniqueId = Math.round((Math.pow(36, 20 + 1) - Math.random() * Math.pow(36, 20))).toString(36).slice(1);
chrome.storage.sync.set({'unique_app_id': uniqueId});
callback(uniqueId);
}
});
}
}]);
angular.module('chromeExtension')
.controller('sampleController',['$scope', 'customService', function ($scope, customService) {
customService.getUniqueId(function(uniqueId) {
console.log("Unique: ", uniqueId);
});
}]);
相关文章:
- Javascript返回值只在循环中返回一次
- XMLHttpRequest未返回值-状态202
- 根据是否解析了 Promise 从函数返回值
- Angular,函数在(模型)工厂中返回值
- AngularJS错误:提供程序必须从$get工厂方法返回值
- 如何从客户端的数组中获取用户输入和返回值
- Javascript中带有返回值的嵌套函数
- 为变量分配多个nodejs导出返回值时出现问题
- 通过回调从onreadystatechange返回值
- 从Ajax函数返回值
- chrome.storage.sync.get未返回值-Angular服务
- 赋值 Angular 2 中 Http 订阅方法返回的值
- 如何使angular在继续之前等待函数返回值
- 将Angular $http返回值获取到另一个对象中
- Angular - factory应该从第三方回调中返回值
- Angular递归方法没有返回值
- Angular:在我在控制器中设置返回值之前,我怎么能等待服务中的承诺被解析呢?
- 在angular js中,从链接函数中返回值到更高的作用域
- 在我自己的Angular服务中,如何将返回值返回给调用该服务的控制器
- Angular ng show不会根据函数返回值显示/隐藏