0

Ich erstelle eine Chrome-Erweiterung mit Winkel & versuche, chrome.storage zu verwenden, um & zu setzen, bekomme zufällig generierte ID, aber zu der Zeit "bekomme" diese ID nicht, unten ist mein Code:chrome.storage.sync.get kein Rückgabewert - Winkeldienste

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; 
      } 
     }); 
    } 
}]); 

also, wenn ich dieses GetUniqueID in meinem Controller nenne ich nicht definiert bin immer ich auch verwendet Timeout dachte da chrome.storage.sync async Aufruf ist so, dass der Grund, aber kein Glück sein könnte. Unten ist mein Controller, wo ich diese Funktion nenne:

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 
}]); 
+0

Was nicht definiert ist? 'chrome.storage' oder' data.unique_app_id'? Wenn früher, hast du 'Speicher'-Berechtigungen deklariert? –

+0

Rückgabewert beim Aufruf von getUniqueId ist nicht definiert, dieser Wert sollte von data.unique_app_id & yes sein Ich habe die Berechtigung –

+0

deklariert Da 'chrome.storage.sync.get' ein asynchroner Aufruf ist, könnten Sie auch angeben, wie Sie' getUniqueId' aufrufen ? –

Antwort

1

chrome.storage.sync.get ist ein asynchroner Aufruf, kann man nicht direkt die Ergebnisse erhalten.

Eine Abhilfe wäre eine Rückruf das Hinzufügen und console.log in den Rückruf anrufen, ich bin nicht vertraut mit angular.js aber Beispielcode wäre:

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); 
    }); 
}]); 
+0

Danke, das hat funktioniert ... :) –