2017-03-07 60 views
1

沒有人知道如何將Ionic2 Storage.get值分配給我的本地變量?如果我在.then中使用console.log,可以正常工作,但它似乎只存在於該函數/方法中。 大多數例子我看,說明如何「讓」我的數據,但沒有真正把它應用到我的其他代碼Ionic2 Storage Promise.all範圍

-Thanks

import { Storage } from '@ionic/storage'; 

export class MyApp { 

favDessertMax: string; 
favDessertRuby: string; 

constructor(storage: Storage) { } 

storage.ready().then(() => { 

    this.storage.set('Max', 'Apple sauce'); 
    this.storage.set('Ruby', 'Banana split'); 


    Promise.all([ 
     this.storage.get('Max'), 
     this.storage.get('Ruby'), 
    ]) 
    .then(([val1,val2]) => { 
     this.favDessertMax = val1; 
     this.favDessertRuby = val1; 
     console.log(val1 + " " + val2); //values work here 
    }) 
    console.log(val1 + " " + val2); // values don't work out here (or anywhere else) 
    }); 

    storyTime() { // Need value to work here 
    let myStory = 'Max likes ' + this.favDessertMax + ' and Ruby Likes 'this.favDessertRuby'; 
    return myStory; 
    } 

} 

回答

1

Promise.all的設置數據到本地變量。它是異步的,因此您可能無法獲得您撥打storyTime()。 您必須鏈接承諾,以確保您將獲得數據。

getData(){ 

    return Promise.all([ 
      this.storage.get('Max'), 
      this.storage.get('Ruby'), 
     ]) 
     .then(([val1,val2]) => { 
      this.favDessertMax = val1; // from 'Max' 
      this.favDessertRuby = val2; // from 'Ruby' 
      return [val1,val2];//return value in then. 
      console.log(val1 + " " + val2); //values work here 
     }) 
     }); 
    } 

storyTime() { // Need value to work here 
    return this.getData().then([val1,val2]=>{ 
    let myStory = 'Max likes ' + val1 + ' and Ruby Likes '+ val2 + '; 
    return myStory; 
    }); 
    }