2017-04-03 22 views
0

我正在使用離子存儲,並且它返回一個Promise ...,這實際上是不切實際的。離子存儲,如何在Promise範圍內保持簡單

我需要從存儲中獲取一個值,並根據它的布爾值做一些事情。

這是代碼我在角1:

$scope.isUser = UserService.getUser() ? true : false; 
$scope.isUserTemp = storageService.get("userTemp") ? true : false; 
$scope.data.showLoginClose = ($scope.isUser || $scope.isUserTemp || !$rootScope.isMobile); 

下面是打字稿新代碼:

let isUser: boolean; 
    let isUserTemp: boolean; 
    this.storage.ready().then(() => { 
     this.storage.get('userTemp').then((val) => { 
      isUserTemp = true ; 
      isUser = UserService.getUser() ? true : false; 
      this.data.showLoginClose = (isUser || userTemp || !this.isCordova.f()); 
     }) 
     .catch((e) => { 
      isUserTemp = false ; 
      isUser = UserService.getUser() ? true : false; 
      this.data.showLoginClose = (isUser || userTemp || !this.isCordova.f()); 
     }) 
    }); 

3行代碼和14號線,這不是一個進步。對於所有的情況(isUser true,userTemp:true; isUser false,userTemp:true;等等),你能幫我寫一些乾淨的Angular2/typecript的Promise範圍內的東西嗎?

+1

$ scope在角度2中不存在..它是角度1的概念..你可以添加你的類嗎? –

+0

編輯。那是我的舊代碼遷移 – Louis

+0

@suraj對不起,我重寫了我的問題,目前還不清楚。 – Louis

回答

0

基於@VinceOPS,但有固定的邏輯,因爲離子存儲基於localForage,.then()是即使你要找的變量不存在於存儲執行,在這種情況下valnull

let that = this; 
    this.storage.ready().then(() => { 
     return this.storage.get('userTemp'); 
    }) 
    .then(retrieved => updateLoginClose(retrieved)) 
    .catch(e => console.error('ERROR: could not read Storage, error:', e)); 
    function updateLoginClose(retrieved) { 
     let isUserTemp:boolean; 
     if (retrieved !== null) { 
      isUserTemp = true; 
     } else { 
      isUserTemp = false; 
     } 
     that.data.showLoginClose = isUserTemp || that.UserService.getUser() || !that.isCordova.f(); 
    } 
+0

這不是「固定邏輯」,而是錯誤的編碼和太多的代碼行。 請參閱http://stackoverflow.com/questions/43182646/ionic-storage-how-to-stay-simple-in-the-promise-scope/43183339#comment73477720_43183339 – VinceOPS

0

刪除無用的變量isUserTemp(這是剛剛設置爲truefalse,這意味着你不需要給它一個條件涉及,因爲你已經知道它的價值...)和isUser(只依賴於後UserService.getUser()),這裏就是你:

this.storage.ready().then(() => { 
    return this.storage.get('userTemp'); 
}).then((val) => { 
    this.data.showLoginClose = (UserService.getUser() || !this.isCordova.f()); 
}).catch((e) => { 
    this.data.showLoginClose = (UserService.getUser() || !this.isCordova.f()); 
}); 

我覺得喜歡的事是錯誤的邏輯。 未成年重構之後,你可能有類似:

function updateLoginClose(isUserTemp: boolean) { 
    this.data.showLoginClose = isUserTemp || UserService.getUser() || !this.isCordova.f(); 
} 

this.storage.ready().then(() => { 
    return this.storage.get('userTemp'); 
}) 
.then(val => updateLoginClose(!!val)) 
.catch(() => updateLoginClose(false)); 

請介意你應該做的變量vale的東西,否則,不申報。

編輯 - 考慮val

+0

將「this」工作在'function updateLoginClose(...'? – Louis

+0

@Louis in typecript [class](https://www.typescriptlang.org/docs/handbook/classes.html)成員函數中。是 –

+0

是的,我看到了,所以@VinceOPS寫的是不是打字稿,是嗎?如何刪除瓦爾'val'和'e'的聲明? – Louis