$资源加载之后才AngularJS负载视图 [英] AngularJS load view only after $resource has loaded
问题描述
在我的项目,我想在这些网页的请求完成后,才页面加载。比如我有一个包含NG-init重新getArtistsInfo视图。我想,要getArtistsInfo请求后,才装入中显示包含NG-INIT页:
In my project I want the pages to load only after the requests on those pages are finished. For example I have a view that contains an ng-init to getArtistsInfo. I want that the page that contains that ng-init to be shown only after the request to getArtistsInfo have loaded:
<div class="row" ng-controller="ArtistController" ng-init="getArtistInfo(params)">
<div class="col-lg-2 col-md-2 col-sm-3 col-xs-4">
<img ng-src="{{ artist.image_url }}" alt="{{ artist.name }}">
</div>
<div class="col-lg-10 col-md-10 col-sm-9 col-xs-8">
{{ artist.bio }}
</div>
</div>
为了使请求传递给后台API我使用资源:
To make the request to the backend api I use resources:
angular.module('ArtistService', []).factory('Artist', ['$resource',
function ($resource) {
return $resource('/api/artists/:artistId', {
artistId: '@id'
},
{
getArtistInfo: {
method: 'GET',
url: '/api/artists/getArtistInfo'
}
});
}
]);
在控制器我有:
angular.module('ArtistController', []).controller('ArtistController', ['$scope', 'Artist', '$location', '$routeParams',
function ($scope, Artist, $location, $routeParams) {
$scope.getArtistInfo = function (params) {
$scope.artist = Artist.getArtistInfo(params);
}
$scope.params = $routeParams;
}
]);
我怎样才能使整个页面加载后,才收到来自getArtistInfo请求的响应?
我已经使用$ routeProvider决心尝试,但似乎并没有工作。
非常感谢你!
How can I make the whole page load only after I receive the response from the getArtistInfo request? I have tried using resolve in $routeProvider but that doesn't seem to work. Thank you very much!
推荐答案
您使用 ngRoute
模块?在这种情况下,你可以添加一个决心参数加载艺术家信息(参见: https://开头的文档.angularjs.org / API / ngRoute /供应商/ $ routeProvider)。如果下决心参数返回一个承诺的事件($资源做到这一点),路由器等待的承诺得到解决,所以你的情况,它会等到艺术家信息已经被加载:
You use the ngRoute
module? In this case you can add a resolve parameter to load the artist info (see: https://docs.angularjs.org/api/ngRoute/provider/$routeProvider). If a resolve parameter returns a promise event ($resource does this), the router waits for the promise to be resolved, so in your case, it would wait until the artist info has been loaded:
$routeProvider.when('...', {
controller: 'ArtistController',
// ...
resolve: {
artist: ['Artist', '$route', function(Artist, $route) {
return Artist.getArtistInfo($route.current.params).$promise;
}]
}
})
和控制器使用加载艺术家:
and use the loaded artist in the controller:
.controller('ArtistController', [..., 'artist', function(..., artist) {
$scope.artist = artist; // This is the loaded artist
}]);
这篇关于$资源加载之后才AngularJS负载视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!