我正在写一个Angular应用程序。我需要方法getData()来始终返回一个promise。因此,如果从本地存储中检索数据并且它不为null,则应该将其作为promise返回,而不调用$ http.get part。
我该怎么写呢?
getData() {
var data = localStoradge.getItem('data');
if (data == null) {
return $http.get('url').then(function(response){
data = response;
return data
})
}
}
答案 0 :(得分:9)
如果数据已经可用,则返回已解决的promise(使用ES6语法):
function getData() {
var data = localStorage.getItem('data');
if (data == null) {
return $http.get('url');
} else {
// return promise that is already resolved
return Promise.resolve(data);
}
}
然后,您可以始终使用该接口作为承诺,无论数据是否已经可用。
注意:由于您在.then()
处理程序中所做的只是返回数据,因此您可以完全删除它。
或者,使用$ q Angular语法,它看起来像这样:
function getData() {
var data = localStorage.getItem('data');
if (data == null) {
return $http.get('url');
} else {
// return promise that is already resolved
return $q.resolve(data);
}
}
答案 1 :(得分:1)
$ q.when()执行技巧angular $q API doc。同样有帮助:$http API doc。
function getData() {
var data = localStoradge.getItem('data');
if (!data) {
// assigning the promise returned by $http.get to the data variable
data = $http.get('url').then(function(response) {
// setting the data to local storage so it will be fetched from there the next time
// the response body of a $http response is in response.data
// see $http API doc linked above..
localStoradge.setItem('data', response.data);
// returning this will make the promise resolve to the the content of the resource found at 'url'
return response.data;
});
}
// $q.when always returns a promise.
// If data was found in the local storage that data will be wrapped in a promise which will resolve automatically right away.
// If the local storage was not there the data variable will be the promise we get from $http and $q.when will return that promise.
// In both cases your getData method returns a promise which resolves to your data
return $q.when(data);
}
答案 2 :(得分:0)
确保注入$q
function getData() {
var data = localStoradge.getItem('data');
if (data == null) {
return $http.get('url')
} else {
return $q.resolve(data)
}
}
答案 3 :(得分:0)
使用$ q来处理Angular中的promise:
function getData() {
let data = localStorage.getItem('data');
let deferred = this.$q.defer();
this.$http
.get(data)
.success(deferred.resolve)
.error(deferred.reject);
return deferred.promise;
}