Ionic2存储承诺.所有范围



有人知道如何分配一个ionic2 storage.ge value to to我的本地变量吗?如果我在。我看到的大多数示例,显示如何"获取"我的数据,但没有真正将其应用于我的其他代码

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

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

相关内容

  • 没有找到相关文章

最新更新