0

我正在尝试使用服务来获取用户的个人资料信息以显示在模板的标题中。

问题是我的控制器中的变量在服务实际返回任何东西之前被设置(或者至少看起来是这样)。

应用程序.js

// This gets the basic information that is needed for every page
myapp.service('base', function($http) {

    this.getProfile = function() {
        // Get the logge din users info
        $http.get(baseUrl+'v1/users?api_key=1234')
            .success(function(response) {
                console.log('base response = '+response);
                return response;
            })  
    }

});

profile.js

myapp.controller('ProfileController', ['$scope', '$http', 'base', function($scope, $http, base) {

    base.getAuthHeader();
    $scope.profile = base.getProfile();
    console.log('$scope.profile = '+$scope.profile);        
}]);

在我的萤火虫中,这是按照这个确切顺序的输出:

$scope.profile = undefined
base repose = [object Object]

这条线是如何被console.log('$scope.profile = '+$scope.profile);调用的console.log('base response = '+response);

4

1 回答 1

1

您需要使用回调。

myapp.service('base', function($http) {

    this.getProfile = function() {
        // Get the logge din users info
        $http.get(baseUrl+'v1/users?api_key=1234')
            .success(function(response) {
                // this code is async
                // it wont fire as a part of the execution block
                // but rather on its own once the `$http.get` returns
                console.log('base response = '+response);
                return response; // also this return returns
                // the .success function not the .getProfile function
            })  
    }

});

使用回调,您的代码将如下所示:

myapp.service('base', function($http) {
                               // accept a function as an argument
    this.getProfile = function(callback) {
        // Get the logge din users info
        $http.get(baseUrl+'v1/users?api_key=1234')
            .success(function(response) {
                console.log('base response = '+response);
                // fire that function when response is available
                callback(response);
            })  
    }

});

然后在控制器中

myapp.controller('ProfileController', ['$scope', '$http', 'base', function($scope, $http, base) {

    base.getAuthHeader();
    base.getProfile(function(response){
        $scope.profile = response;
        console.log('$scope.profile = '+$scope.profile);        
    });

}]);

或者您可以使用Promise而不是回调来处理异步性质。

于 2013-11-11T02:14:12.217 回答