当http请求正在进行时,如何获取我的控制器的数据?

我有以下控制器

1) introCtrl

2)ArticleCtrl

3)articleService(服务)

现在我正在发送来自introCrtl的http请求

.controller('IntroCtrl', function($scope, articleService) { articleService.getArticles(); }); 

和AricleCtrl是

  .controller('ArticleCtrl', function($scope,$rootScope,articleService) { $scope.articles = articleService.fetchArticles(); }) 

和我的服务是

 .service('articleService', function ($http, $q) { var articleList = []; var getArticles = function() { $http({ url: "muylink,co,", data: { starLimit: 0, endLimit: 150,created_date: 0 }, method: 'POST', withCredentials: true, }).success(function (data, status, headers, config) { articleList.push(data); }).error(function (err) { console.log(err); }) }; var fetchArticles = function() { return articleList[0]; } return { getArticles: getArticles, fetchArticles: fetchArticles }; }); 

哪个也工作正常。 现在的问题是

有时我的HTTP请求发送响应迟了,我什么都没有

$ scope.articles

我们可以在这里实施手表 我需要在这里实现$ watch。 我不想实现诺言。 因为我想在场景后面运行http请求。

谢谢

如果你使用ui-router切换到基于状态的设置,那么你可以这样做:

 $stateProvider.state('myState', { url: 'the/url/you/want', resolve:{ articleService: 'articleService' // you are dependency injecting it here, articles: function (articleService) { return articleService.getArticles.$promise; } }, controller: 'IntroCtrl' }) // then your controller can just inject the articles and they will be resolved before your controller loads so you it will always be fetched prior .controller('IntroCtrl', function($scope, articles) { $scope.articles = articles; }); 

欲了解更多信息,请看看这个

ui路由器信息

所有要做的就是设置文章列表并提供维护function。 当你正在看数组时,最好把它改成string。

在看结果数组中创build函数。

 $scope.$watch( function() { return JSON.stringify($scope.articleList); }, function(newVal,oldVal){ //provide logic here }); 

如果你的服务结果是asynchronous的(比如http请求),你应该返回你服务的承诺。

 .controller('ArticleCtrl', function($scope,$rootScope,articleService) { articleService.fetchArticles().then(function(articles) { $scope.articles = articles; }); }) 

服务

 // not sure about your service logic... simplified: .service('articleService', function ($http, $q) { var articleListPromise ; var getArticles = function() { articleListPromise = $http(/* ...*/); }; var fetchArticles = function() { return articleListPromise.then(function(data) { return data[0]; }); } return { getArticles: getArticles, fetchArticles: fetchArticles }; 

});