Ionic2存储Promise.all范围

问题描述 投票:1回答:1

有谁知道如何将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;
  }

}
angular typescript scope ionic2 storage
1个回答
2
投票

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;
     });
  }
© www.soinside.com 2019 - 2024. All rights reserved.