我只是在玩 angular 和它的 DI。我也尝试使用 Promise 范式,但是在 Chrome 扩展程序中使用它时遇到了一个相当奇怪的问题。
以下代码运行良好。当调用“chromeStorageService”中的对象字面量中的 cb() 时,promise 就解决了。但是当我取消注释返回时chrome.storage.local;
,代码停止工作。我不明白为什么,因为console.log('going to be resolved');
仍然被解雇,但成功警报却没有。提前感谢任何提示:)
https://developer.chrome.com/extensions/storage.html
'use strict';
var app = {};
app = angular.module('options', ['options.controllers']);
app.services = angular.module('options.services', []);
app.services.factory('chromeStorageService', function () {
//return chrome.storage.local;
return {
get: function(id, cb) {
cb();
}
}
});
app.services.factory('storageService', ['chromeStorageService', '$q', function (chromeStorage, $q) {
return new function () {
this.get = function (identifier) {
var defered = $q.defer();
chromeStorage.get(identifier, function (items) {
var error = false//chrome.runtime.lastError;
if (error) {
return defered.reject(error);
}
console.log('going to be resolved');
console.log(defered);
defered.resolve();
});
return defered.promise;
}
}
}]);
app.services.factory('fooService', ['storageService', function (testService) {
return new function () {
this.getAll = function () {
var promise = testService.get('foo');
console.log(promise);
promise.then(
function () {
alert('success');
}, function () {
aler('err');
}
);
}
}
}]);
app.directive('foo', ['fooService', function (fooService) {
return {
restrict:'A',
link:function (scope, elm, attrs, ctrl) {
fooService.getAll();
}
};
}]);
app.controllers = angular.module('options.controllers', ['options.services']);