在 2 个不同的功能之间共享 $scope.数据

sharing $scope.data between 2 different function

本文关键字:共享 之间 scope 数据 功能      更新时间:2023-09-26
getTopicContent.request().finally(function(){
    $scope.loader= false;
}).then(function(response){
    $scope.threadContent = response.data;

})

$scope.loadPages = function($scope) {
    console.log($scope.threadContent.totalPages);
}

getTopicContent 是服务,但我希望 $scope.threadContent 可以与 $scope.loadPages 函数共享?

由于您是异步加载内容的,因此您不能期望数据以同步方式提供。 loadPages函数在访问数据之前应依赖于 promis 解析。例如,您可以按这种方式重写代码:

function getContent() {
    return getTopicContent.request().then(function (response) {
        return response.data;
    }).finally(function () {
        $scope.loader = false;
    });
}
$scope.loadPages = function ($scope) {
    getContent().then(function(data) {
        $scope.threadContent = data;
        console.log($scope.threadContent.totalPages);
    });
}

另请阅读此相关问题描述。