AngularJS: How to get $http result as returned value of a function?

匆匆过客 提交于 2019-12-06 08:09:14

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}}">

* Note that ng-init could certainly be replaced with an in-controller initialization.

JS:

$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";
};

Once the response is returned, movie.imgUrl is changed.

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.

rakesh

As you are using ng-repeat, you can pass the whole movie object, and then can add a new property to it:

$scope.getPoster = function (movie) {
    $http({ url: "http://www.omdbapi.com/?t=" + movie.Title + "&y=&plot=short&r=json" }).
            then(function (response) {
                // How can I return response.data.Poster ? 
                movie.imageUrl = response.data.Poster;
            });
};

and then bind ngSrc:

ng-src='{{movie.imageUrl}}'

Here is the working jsFiddle of your case. Note, i have taken sample titles.

You can't call the function in ng-repeat. You need to get the values before its been loaded like using resolve.

     var app = angular.module('myApp',[]);
app.controller('myCtrl',function($http,$scope){

          $scope.movies =[{Title:'gene',Owner:'Alaksandar'},{Title:'alpha',Owner:'Me'}];
            angular.forEach($scope.movies,function(movie){
                $http.get("http://www.omdbapi.com/?t="+movie.Title+"&y=&plot=short&r=json").
                        success(function (response) {
                            movie['poster'] = response.Poster;
                    });


            });
});

Here's another approach, this may work better for you.

Template:

<div class="col-sm-6 col-md-3" ng-repeat="movie in getMovies">
<div class="thumbnail">
    <img class="poster" ng-src="{{movie.Poster}}" alt="{{movie.Title}}">
    <div class="caption">
        <h3>{{movie.Title}}</h3>
        <p>{{movie.Owner}}</p>
    </div>
</div>

Service:

function getMovieData(movies) {
return {
    loadDataFromUrls: (function () {
        var apiList = movies;

        return $q.all(apiList.map(function (item) {
            return $http({
                method: 'GET',
                url: "http://www.omdbapi.com/?t=" + item + "&y=&plot=short&r=json"
            });
        }))
        .then(function (results) {
            var resultObj = {};
            results.forEach(function (val, i) {
                resultObj[i] = val.data;
            });
            return resultObj;        
        });
    })(movies)
};
};

Controller:

var movies = ["gladiator", "seven"];  

$scope.getMovies = getMovieData(movies);

function getMovieData(){
dataService.getMovieData(movies).loadDataFromUrls
  .then(getMovieDataSuccess)
  .catch(errorCallback);
}


function getMovieDataSuccess(data) {
    console.log(data);
    $scope.getMovies = data;
    return data;
  } 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!