chrome.storage.sync.get未返回值-Angular服务

chrome.storage.sync.get not returning value - Angular services

本文关键字:返回值 -Angular 服务 get storage sync chrome      更新时间:2023-09-26

我正在使用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);
    });
}]);