gpt4 book ai didi

javascript - 操作由 Promise AngularJS 返回的返回变量

转载 作者:行者123 更新时间:2023-12-03 02:05:26 25 4
gpt4 key购买 nike

所以,我被困在这里很可能是因为我对 Promise 对象的理解有限。

我从工厂获取数据的函数是

    $scope.getLogoFromService = function() {
console.log('getLogoFromService called');
var promise =
logoService.getLogo();
promise.then(
function(payload) {
console.log(payload.data.home_header.logo.file_path);
$scope.logoPath = payload.data.home_header.logo.file_path;
},
function(errorPayload) {
$log.error('failure loading logo', errorPayload);
});
};

如果我执行 {{logoPath}} 以及在函数内部进行 console.log 操作,则可以在 View 上访问该变量,但在其他函数中则无法访问该变量。

   $scope.UpdateLogo = function ()
{
console.log('UpdateLogo called');
console.log($scope.logoPath);
}

返回未定义。

我的服务代码,以防万一您需要查看

App.factory('logoService', function($http) {
return {
getLogo: function() {
return $http.get('cms/general');
}
}
});

最佳答案

看起来您在 http 调用返回之前正在调用 UpdateLogo,我建议您这样处理:

$scope.getLogoFromService = function() {
console.log('getLogoFromService called');
var promise = logoService.getLogo();

promise.then(
function(payload) {
console.log(payload.data.home_header.logo.file_path);
$scope.logoPath = payload.data.home_header.logo.file_path; // For use in the view.
return $scope.logoPath; // Return the logopath to the next function in the chain.
},
function(errorPayload) {
$log.error('failure loading logo', errorPayload);
}
);

return promise;
};

$scope.UpdateLogo = function() {
console.log('UpdateLogo called');
$scope.getLogoFromService().then(function(logoPath) {
console.log('getLogoFromService resolved!');
console.log(logoPath);
});
}

由于 logoPath 已分配给范围,从技术上讲,您不必担心将其传递到 promise 链,但这是最佳实践,所以我首先建议它,或者这也将工作:

$scope.getLogoFromService = function() {
console.log('getLogoFromService called');
var promise = logoService.getLogo();

promise.then(
function(payload) {
console.log(payload.data.home_header.logo.file_path);
$scope.logoPath = payload.data.home_header.logo.file_path; // For use in the view.
},
function(errorPayload) {
$log.error('failure loading logo', errorPayload);
}
);

return promise;
};

$scope.UpdateLogo = function() {
console.log('UpdateLogo called');
$scope.getLogoFromService().then(function() {
console.log('getLogoFromService resolved!');
console.log($scope.logoPath);
});
}

在本例中,我们只是将 Promise 用作“数据现在可用”通知,但我们实际上并未传递数据,因为它已分配给 $scope 并且这两个函数都可以访问它。

整个事情也可以压缩为一个更简单的函数,但我保持了你原来的结构完整。

关于javascript - 操作由 Promise AngularJS 返回的返回变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49831142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com