我试图从控制器方法中调用带有参数的服务,但收到一条错误消息说它不是函数。这是我的代码:

(function (){

angular.module('app.uploadedReleases')
        .controller('UploadedReleasesController', UploadedReleasesController)
        .controller('ModalController', ModalController);


UploadedReleasesController.$inject = ['$log', '$scope', '$modal', 'ReleaseService', 'TrackService'];
function UploadedReleasesController ($log, $scope, $modal, releaseService, trackService){

        vm.selectTrack = selectTrack;

       function selectTrack(album, track, index){

        trackService.currentTrack(album.slug, track.fileName).then(function(responseValue){
            vm.temp = responseValue;
        });
        vm.formTrack = vm.selected.track;
    }
}


这是我的名为trackService的服务:

angular.module('app.services')
        .service('TrackService', TrackService);

TrackService.$inject = ['$http', '$q'];

function TrackService($http, $q){
    var trackService = {};

    var releasesUrl = 'http://localhost:8080/api/releases';
    trackService.currentTrack = currentTrack;

        function currentTrack(releaseSlug, trackSlug){
        var trackUrl = releasesUrl + '/'+ releaseSlug + '/' + trackSlug + '/track';
        var deferred = $q.defer();

        $http.get(trackUrl).then(function(trackResponse){
            return deferred.resolve(trackResponse);
        }, function(error){
            return deferred.reject({msg: 'Error while getting the current track details'})
        });
      return deferred.promise;
    }
}


知道为什么我会在控制器中出现错误:TypeError: trackService.currentTrack is not a function

最佳答案

我要说的第一件事是,您正在创建服务,然后应将方法绑定到this上下文,而不是创建对象。

var trackService = {};


会变成

var trackService = this;


但是从服务返回自定义对象也没有错。因此,在当前情况下,您错过了退还它的机会。在您的服务代码末尾添加

return trackService


仍然对服务和工厂的工作方式感到困惑,我建议您阅读this answer



您应该从以自定义方式创建的trackService.currentTrack方法返回一个Promise。

trackService.currentTrack = currentTrack;
function currentTrack(releaseSlug, trackSlug){
    var trackUrl = releasesUrl + '/'+ releaseSlug + '/' + trackSlug + '/track';
    var deferred = $q.defer();
    $http.get(trackUrl).then(function(trackResponse){
        return deferred.resolve(trackResponse);
    }, function(error){
        return deferred.reject({msg: 'Error while getting the current track details'})
    });
    return deferred.promise; //returned promise
}




相反,您应该做自己的自定义承诺,将其视为反模式,以实现通过$http.get方法返回的承诺的地方,您应该利用它。

重构版本

trackService.currentTrack = currentTrack;
    function currentTrack(releaseSlug, trackSlug){
    var trackUrl = releasesUrl + '/'+ releaseSlug + '/' + trackSlug + '/track';
    return $http.get(trackUrl).then(function(trackResponse){
        return trackResponse;
    }, function(error){
        return {msg: 'Error while getting the current track details'};
    });
}

08-08 05:29