【问题标题】:Ionic2 Storage Promise.all scopeIonic2 存储 Promise.all 范围
【发布时间】:2018-03-02 11:31:41
【问题描述】:

有谁知道如何将 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】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-02
      • 1970-01-01
      • 2012-08-28
      • 2015-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多