Angularjs 控制器在服务方法返回之前从服务中分配变量

Angularjs controller assigning variable from service, before service method returns

本文关键字:服务 分配 变量 返回 控制器 方法 Angularjs      更新时间:2023-09-26

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

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

应用.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;
            })  
    }
});

简介.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);之前是如何被调用的?

你需要使用回调。

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

或者你可以用承诺而不是回调来处理异步性质。