在我的角度项目中,我有两个ts文件,如下所示:
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);//????
}
}
从data.ts
,如何将数据值返回到main.ts
?
答案 0 :(得分:1)
你的data.ts方法应该只返回请求本身,而不是订阅它:
GetItemDataFromStorage(current){
return this.storage.get(current);
};
并在您的main.ts方法中订阅并接收数据:
fetchThumbData(){
var data = this.itemStorage.GetItemDataFromStorage(this.dataNumber).then((data) => {
console.log(data);//????
});
}
答案 1 :(得分:1)
您的Data.ts很可能会返回一个承诺 Main.ts
export class item_thumb {
constructor(public itemStorage: itemFromStorage) {
};
fetchThumbData(){
let promise = this.itemStorage.GetItemDataFromStorage(this.dataNumber);
promise.then(data => console.log(data));
}
}
要同步获取值:Get the value of a Javascript Promise in a synchronous way