AngularJS:如何获得$ HTTP结果作为函数的返回值? [英] AngularJS: How to get $http result as returned value of a function?
问题描述
在我的控制,我需要一个函数,它接受一个参数,并从服务器返回一个URL。事情是这样的:
Inside my controller I need a function that takes a parameter and returned a URL from server. Something like this:
$scope.getPoster = function(title) {
return $http.get("http://www.omdbapi.com/?t=" + title + "&y=&plot=short&r=json");
};
和里面我认为我需要通过标题这种方式获得结果为的src
为 NG-SRC
And inside my view I need to pass the title this way and get result as src
for ng-src
:
<div class="col-sm-6 col-md-3" ng-repeat="movie in movies">
<div class="thumbnail">
<img class="poster" ng-src="{{getPoster(movie.Title)}}" alt="{{movie.Title}}">
<div class="caption">
<h3>{{movie.Title}}</h3>
<p>{{movie.Owner}}</p>
</div>
</div>
</div>
我知道在 $ HTTP
从来没有回,我马上需要,因为所有通信都是异步的所以我需要使用承诺数据的HTTP通信:
I know the HTTP communications on $http
never ever return data that I need immediately because all communications are asynchronous So I need to use promise:
$scope.getPoster = function(title) {
$http({ url: "http://www.omdbapi.com/?t=" + title + "&y=&plot=short&r=json" }).
then(function (response) {
// How can I return response.data.Poster ?
});
};
所以我的问题是,如何才能换来 getPoster
函数的响应,结果呢?
你知道吗?
So my question is that How can I return the response as result for getPoster
function?
Any idea?
推荐答案
如果您通过电影
到 getPoster
功能,而不是标题
,它应该工作;和一个变量绑定到 NG-SRC代替
,它应该工作。 getPoster
函数的返回
If you pass movie
to getPoster
function, instead of title
, it should work; and bind a variable to ng-src
instead of the return of the getPoster
function, it should work.
此外,您可以显示一个占位符,而你正在等待回应:
Also, you could display a placeholder while you are waiting for the response:
HTML:
<img class="poster"
ng-init="movie.imgUrl = getPoster(movie)"
ng-src="{{movie.imgUrl}}"
alt="{{movie.Title}}">
<子> *请注意, NG-INIT
当然可以被替换为的在控制器的初始化的。
* Note that ng-init
could certainly be replaced with an in-controller initialization.
记者:
$scope.getPoster = function(movie) {
$http({ url: "http://www.omdbapi.com/?t=" + movie.Title+ "&y=&plot=short&r=json" })
.then(function (response) {
movie.imgUrl = response.data.Poster;
});
return "/img/poster-placeholder.png";
};
一旦响应
返回, movie.imgUrl
更改。
因此,图像会自动执行下消化周期新源进行更新。
So, the image will automatically be updated with the new source in the next digest cycle.
通过这个例子,你将不再需要返回的承诺。
With this example, you won't need to return the promise.
这篇关于AngularJS:如何获得$ HTTP结果作为函数的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!