gpt4 book ai didi

javascript - 使用 $http 刷新来自服务的数据时, Angular View 不更新

转载 作者:行者123 更新时间:2023-11-30 15:46:21 25 4
gpt4 key购买 nike

这可能是一个被问过一万次的问题,但我仍然找不到合适的解决方案。

我只是有一个 Controller 从服务获取数据的经典示例,该服务又使用 $http 从 API(或 JSON 文件)异步获取一些数据。因为 Controller 中的数据是对服务中对象的引用,所以我希望数据在服务完成其工作时发生变化,因此我希望 View 能够更新。正如您在下面的代码片段中所见, View 保留了初始值。

因此,我的两个问题:

  1. 这是一个好的模式吗?想象一下, Controller 不止一个,并且在某个时候需要重新获取数据(并因此在任何 Controller 中更新)
  2. 为什么 View 没有更新?

请记住,我不想使用 $scope(如果可能)、$rootSscope 或 $watch。

var app = angular.module('myApp', [])
.service('Service', ['$http', service])
.controller('Controller', ['Service', controller]);


function controller(Service){
var c = this;
c.items = [
{'title': 'Default title1'},
{'title': 'Default title2'}
];
c.items = Service.data;
}

function service($http, $scope){
var data = [
{'title': 'olddatatitle'}
];
$http({
method: 'GET',
url: 'https://jsonplaceholder.typicode.com/posts?userId=1',
cache: true
}).then(function(response){
data = response.data;
});
return {
data: data
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" >
<ul ng-controller="Controller as c">
<li ng-repeat="item in c.items">
{{item.title}}
</li>
</ul>
</div>

最佳答案

您的问题是一个异步问题...您不想在您的服务中从 $http 获取您的数据,并期望它在您的 Controller 准备就绪时准备就绪。不要尝试返回数据,而是返回数据 promise :

function service($http, $scope){
//var data = [
// {'title': 'olddatatitle'}
//];

return {
getData: function() {
return $http({ // calls to $http return a promise object
method: 'GET',
url: 'https://jsonplaceholder.typicode.com/posts?userId=1',
cache: true
});
}
}

这样你的 Controller 就会准确地知道数据何时可以被消费:

function controller(Service){
var c = this;
//c.items = [
// {'title': 'Default title1'},
// {'title': 'Default title2'}
//];
Service.getData().then(function(response) { // the promise object allows you to assign data only when it's ready
c.items = response.data
});
}

关于javascript - 使用 $http 刷新来自服务的数据时, Angular View 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40008133/

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