gpt4 book ai didi

javascript - AngularJS 服务返回数据而不是 promise

转载 作者:行者123 更新时间:2023-11-29 16:57:13 24 4
gpt4 key购买 nike

我有一个关于在 AngularJS 应用程序中使用服务或工厂的问题。

我想编写一个服务,该服务将从我可以在我的 Controller 中使用的 Api 返回数据。

假设我想像 $scope.people = myPeopleService.getPeople(); 这样的电话在我的服务中想检查我是否已经有人并返回那些人,否则我想做一个 $http.get() 并在我的服务中填充人员然后返回他们。我不想在我的 Controller 中有 .then 。这可能吗?

最佳答案

如果您不想将 promise 返回给您服务的消费者:

.service('...', function ($http) {
var cachedResponse;

this.getStuff = function () {
if (cachedResponse) {
return cachedResponse;
}

return $http.get('someUrl')
.then(function (response) {
cachedResponse = response;
return response; // Return the response of your $http call.
});
};
});

关于javascript - AngularJS 服务返回数据而不是 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31385019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com