用AngularJS传递一个变量给一个服务

Pass a variable to a service with AngularJS?

本文关键字:一个 服务 变量 AngularJS      更新时间:2023-09-26

我正在构建一个应用程序来跟踪电影和他们的信息,我是Angular的新手,我不能真的确定如何将变量传递给这个服务。我希望url是一个变量,而不是硬编码。最好的方法是什么?

tmdb.service('tmdbService', function($http, $q){
    var deferred = $q.defer();
    $http.get('https://api.themoviedb.org/3/movie/popular?api_key=jkhkjhkjhkjh').then(function(data){
        deferred.resolve(data);        
    });
    this.getMovies = function(){
        return deferred.promise;
    }
});
tmdb.controller("tmdbController", function($scope, tmdbService){
    var promise = tmdbService.getMovies();
    promise.then(function(data){
        $scope.movies = data;
        //  console.log($scope.movies);
    })
}); 

不需要(在这种情况下)使用$q.defer(),因为$http已经返回一个promise。因此,您的服务代码可以简化为:

tmdb.service('tmdbService', function($http){
    this.getMovies = function(){
        return $http.get('https://api.themoviedb.org/3/movie/popular?api_key=jkhkjhkjhkjh');
    }
});

然后,如果你想发送一个参数,你可以这样做:

tmdb.service('tmdbService', function($http){
    this.getMovies = function(movieId){
        return $http.get('https://api.themoviedb.org/' + movieId + '/movie/popular?api_key=jkhkjhkjhkjh');
    }
});
在你的控制器中,你现在可以发送movieId:
tmdb.controller("tmdbController", function($scope, tmdbService){
    tmdbService.getMovies(3).then(function(response){
        $scope.movies = response.data;
        //  console.log($scope.movies);
    })
}); 

我通常这样做,我觉得这样更简洁,更易读:

tmdb.service('tmdbService', [function($http) {
    return {     //simple mapping of functions which are declared later
        fn1: fn1,
        fn2: fn3
    }
    function f1(param) { //param can be the url in your case
        //fn code example
        return $http.post(param).success(function(response) {
             return response.data;
        })
    }
    function f2(param) {
    }
}]

在控制器中,使用服务:

tmdb.controller('tmdbController', ['$scope', 'tmdbService', function($scope, tmdbService) {
    tmdbService.f1(url).then(function(data) {
         //handle the data here
    })
}])

有几种方法可以实现这个目标。在我看来,没有正确/错误的方法;什么是正确的完全取决于您的需求,这可能会随着应用程序的增长而改变。

特别是对于大型应用程序,您可以定义一个模块来管理url,并将该模块注入到索引应用程序中。

另一种方法是定义一个服务来管理你的url。在这种情况下,你还必须将这个服务注入到你可能需要它的任何其他服务/控制器等中。这样做的缺点是,该服务只对其内部定义的angular模块可用,或者最多只能通过该模块访问。

因此,使用服务样式是如何实现的。

tmdb.service('urlService', function () {
    
    this.urls = {
        url1: 'https://api.themoviedb.org/3/movie/popular?api_key=jkhkjhkjhkjh',
        url2: 'anotherUrl'
    };
});
tmdb.service('tmdbService', ['$http', '$q', 'urlService', function ($http, $q, urlService) {
    var deferred = $q.defer();
    $http.get(urlService.url.url1).then(function (data) {
        deferred.resolve(data);
    });
    this.getMovies = function () {
        return deferred.promise;
    }
}]);

没有绝对的正确/错误的方法;这取决于.

希望对你有帮助。

干杯!