[英]How to assign data returned from $promise to global variable
我有兩個服務, service1 and service2
,我想將service1
的方法調用到service2
。
理想情況下,我想將service1.getMethod()
返回的數據分配給聲明為var result = []
的全局變量。
這是代碼:
.factory('service1', function (dependencies...) {
var getMethod1 = function () {
...//making http get call
return deferred.promise();
};
return {
getMethod1 : getMethod1
};
});
.factory('service2', function (dependencies...) {
var result = [];
var getMethod2 = function () {
Service1.getMethod1().then(function (data) {
result = data;
});
//RUN METHOD
getMethod2();
//Here ideally, I would like result to contain `[object, object, object]`
console.log(result); //instead it prints `undefined`
});
所以,理想情況下,我想使用的將是什么result
在service2's
其他functions
ie result[0].name
等不知道我在做什么是正確的做法。
請提供一個plunker demo or code snippet
示例,如果不確定某件事,請在下面寫評論。
謝謝!
您不能像嘗試那樣使用異步代碼。 嘗試使用result
變量時,它尚未完全填充。 相反,您也應該使getMethod2
返回promise,並使用其then
方法:
.factory('service2', function (dependencies...) {
var getMethod2 = function () {
return Service1.getMethod1();
};
// RUN METHOD
getMethod2().then(function(result) {
console.log(result);
});
});
您還可以緩存返回的數據:
.factory('service2', function (dependencies...) {
var result;
var getMethod2 = function () {
return result ? $q.when(result) : Service1.getMethod1().then(function(data) {
result = data;
return result;
});
};
// RUN METHOD
getMethod2().then(function(result) {
console.log(result);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.