Angular Ionic2存储承诺。所有范围

Angular Ionic2存储承诺。所有范围,angular,typescript,scope,ionic2,storage,Angular,Typescript,Scope,Ionic2,Storage,有人知道如何将Ionic2 Storage.get值分配给我的局部变量吗?如果我在.then中使用console.log,效果很好,但它似乎只存在于该函数/方法中。 我看到的大多数示例都显示了如何“获取”我的数据,但没有真正将其应用到我的其他代码中 -谢谢 import { Storage } from '@ionic/storage'; export class MyApp { favDessertMax: string; favDessertRuby: string; construc

有人知道如何将Ionic2 Storage.get值分配给我的局部变量吗?如果我在.then中使用console.log,效果很好,但它似乎只存在于该函数/方法中。 我看到的大多数示例都显示了如何“获取”我的数据,但没有真正将其应用到我的其他代码中

-谢谢

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;
  }

}

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;
     });
  }