2016-03-17 83 views
1

有人可以幫我將下面的代碼從JavaScript轉換爲TypeScript嗎?Localstorage getitem和setitem 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); 
     }; 
    } 
}()); 

回答

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

+0

非常感謝Basart。 – user3125908

+0

我收到了下面提到的錯誤app/js/components/localstorage/local-storage-service.ts(12,21):錯誤TS7006:參數'$ window'隱含有'any'類型。 app/js/components/localstorage/local-storage-service.ts(18,40):錯誤TS7006:參數'key'隱式具有'any'類型> app/js/components/localstorage/local-storage-service .ts(21,45):錯誤TS7006:參數'值'隱式具有'任何'類型。 – user3125908