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

隐身守侯 提交于 2019-12-07 20:02:13

问题


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

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>  

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 ? 
    });
};

So my question is that How can I return the response as result for getPoster function?
Any idea?


回答1:


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.




回答2:


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



回答3:


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;
                    });


            });
});



回答4:


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


来源:https://stackoverflow.com/questions/29104607/angularjs-how-to-get-http-result-as-returned-value-of-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!