Javascript 在加载模板之前完成http请求
我的模板首先加载,然后触发http请求,因为当我第一次加载页面时,它显示404 image src未在控制台中找到,但在微秒后成功加载数据。通过谷歌搜索,我发现我们可以使用resolve属性来处理这种情况。下面是我对resolve的实现Javascript 在加载模板之前完成http请求,javascript,jquery,angularjs,angular-ui-router,Javascript,Jquery,Angularjs,Angular Ui Router,我的模板首先加载,然后触发http请求,因为当我第一次加载页面时,它显示404 image src未在控制台中找到,但在微秒后成功加载数据。通过谷歌搜索,我发现我们可以使用resolve属性来处理这种情况。下面是我对resolve的实现 var app=angular.module('websiteApp',['ui.router']); app.config(function($stateProvider,$urlRouterProvider,$httpProvider){ $urlRout
var app=angular.module('websiteApp',['ui.router']);
app.config(function($stateProvider,$urlRouterProvider,$httpProvider){
$urlRouterProvider.otherwise("/movies");
$stateProvider.state('movies',
{
url:"/movies",
templateUrl:"views/movies.html",
controller:"moviesController",
resolve:
{
movieslist:moviesController.getallMovies
}
})});
我的控制器:
var moviesController=app.controller('moviesController',
function($scope,movieslist){
$scope.movies=movieslist.data.result
});
moviesController.getallMovies=function($q,$timeout,movieservice)
{
var defer=$q.defer();
$timeout(function(){
defer.resolve(movieservice.getlist());
},1000);
return defer.promise;
}
我的服务:
app.factory('movieservice',function($http,$location){
var movieserviceObj={};
movieserviceObj.getlist=function(){
dataString={mode:'list',page:1,recordsperpage:10};
return $http({ url:'app/api/entertainment.php',data:$.param(dataString),method:'POST'});
};
return movieserviceObj;
}))
我的模板[示例]:
<div class="col-sm-6 col-md-3" ng-repeat="movie in movies">
<img src='public/images/{{movie.image}}' style="width: 175px;"/>
</div>
但是我的movies.html仍然在http请求之前加载(延迟1秒),因此我的控制台错误仍然没有消失。这是在angularjs中实现解析的正确方法吗。来自Angular documentation(): 模块ng中的ngSrc指令 在src属性中使用像{{hash}}这样的角度标记是不正确的:浏览器将从URL获取文本{{hash},直到Angular替换了{{hash}中的表达式。ngSrc指令解决了这个问题 编写它的错误方式:
<img src="http://www.gravatar.com/avatar/{{hash}}"/>
<img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
正确的书写方法:
<img src="http://www.gravatar.com/avatar/{{hash}}"/>
<img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
您是否尝试过ng src
?@davin嘿,谢谢,ng src解决了我的问题。为此浪费了我的1小时。@davin在上面的示例中,如果http调用在1秒之前完成[确实如此]。如何立即返回承诺而不是使用超时。