有人可以帮助我将以下代码从JavaScript转换为TypeScript吗?
(function () {
'use strict';
angular.module('testUi').service('localStorage', localStorage);
localStorage.$inject = ['$window']
function localStorage ($window) {
var storage;
if ($window.localStorage) {
storage = $window.localStorage;
} else {
storage = {
items:[],
getItem: function(key) {
return this.items[key];
},
setItem: function(key,value) {
this.items[key] = value;
}
};
}
//exports
this.get = function (key) {
return storage.getItem(key);
};
this.set = function(key,value) {
storage.setItem(key,value);
};
}
}());
答案 0 :(得分:2)
请注意。 JavaScript 是 TypeScript(see why TypeScript)。所以代码应该在ts文件中编译。
如果您希望将其转换为类,您可以:
class LocalStorage {
static $inject = ['$window'];
constructor($window) {
if ($window.localStorage) {
this.storage = $window.localStorage;
} else {
this.storage = {
items: [],
getItem: function (key) {
return this.items[key];
},
setItem: function (key, value) {
this.items[key] = value;
}
};
}
}
storage: any;
get(key) {
return this.storage.getItem(key);
}
set(key, value) {
this.storage.setItem(key, value);
}
}
angular.module('testUi')
.service('localStorage', LocalStorage);
这使您可以获得服务的记录的公共合同。
我有关于此主题的公开/免费视频:https://www.youtube.com/watch?v=Yis8m3BdnEM