0

In my angular project, I have two ts files as below:

Data.ts

import { Injectable } from '@angular/core';
import { MyStorage } from '../storage';

@Injectable()
export class itemFromStorage {
constructor(public storage: Storage) {  

}

    GetItemDataFromStorage(current){        
        this.storage.get(current).then((val) => {
          return val;  //????    
        }); 
   };    

}

Main.ts

import { itemFromStorage } from '../data'

export class item_thumb {
    constructor(public itemStorage: itemFromStorage) { 

    };  

   fetchThumbData(){
     var data = this.itemStorage.GetItemDataFromStorage(this.dataNumber);
     console.log(data);//????
   }
}

From the data.ts, how do I return the data value to main.ts?

Steve Kim
  • 5,293
  • 16
  • 54
  • 99
  • Read http://blog.ninja-squad.com/2015/05/28/angularjs-promises/. It's about angular 1 promises, but the concept of standard JS promises is exactly the same. – JB Nizet Jul 27 '17 at 22:34
  • 1
    Style note: classes in TypeScript use UpperCamelCase and methods use lowerCamelCase, so your classes should be `ItemFromStorage` and `ItemThumb` and your method should be `getItemDataFromStorage`. – John Montgomery Jul 27 '17 at 22:43

2 Answers2

1

your data.ts method should return only the request itself, without subscribing to it:

    GetItemDataFromStorage(current){        
        return this.storage.get(current);
   }; 

and in your main.ts method subscribe and receive the data:

   fetchThumbData(){
     var data = this.itemStorage.GetItemDataFromStorage(this.dataNumber).then((data) => {
          console.log(data);//???? 
        }); 

   }
t v
  • 199
  • 1
  • 11
  • Please indent your code correctly :) also [hightlighting hints](https://meta.stackexchange.com/questions/184108/what-is-syntax-highlighting-and-how-does-it-work/184109#184109) can make it much easier to read – 0mpurdy Jul 27 '17 at 23:33
1

Most likely your Data.ts is returning a promise.
Main.ts

export class item_thumb {
    constructor(public itemStorage: itemFromStorage) { 
    };  
   fetchThumbData(){
     let promise = this.itemStorage.GetItemDataFromStorage(this.dataNumber);
     promise.then(data => console.log(data));     
   }
}

To get the value synchronously: Get the value of a Javascript Promise in a synchronous way

yonexbat
  • 2,902
  • 2
  • 32
  • 43