Angular中无法在Promise外部获取变量值的问题求助
问题分析与解决方案
核心问题
Promise是异步操作,varResults.then()内的代码会在后续事件循环中执行,而你当前的$scope.finalLocation = varLocationString;是同步执行的——这行代码运行时,varLocationString还没被赋值,所以始终为空。
修复步骤
- 把赋值操作移到Promise回调内:确保在数据准备完成后再给
$scope.finalLocation赋值。 - 替换JSON构建方式:你用字符串拼接后再
JSON.parse的写法极易出错(比如字符串含引号会直接崩溃),直接创建JS对象更安全可靠。 - 优化变量命名(可选):去掉变量名前的
var前缀,改用驼峰式命名,提升代码可读性。
修复后的完整代码
angular.module('example.components') .controller('Locations', ['$scope', 'LocationsService', function ($scope, LocationsService) { let results; let cityName; let isoCode; let useUsersLocation; let latitude; let longitude; let locationString; results = LocationsService.search([], [], [], 99) results.then(results => { $scope.array = results; let i = 0; const myobj = JSON.parse($scope.array[i].properties.weatherLocations); cityName = myobj.fieldsets[0].properties[0].value; isoCode = myobj.fieldsets[0].properties[1].value; useUsersLocation = myobj.fieldsets[0].properties[2].value; latitude = myobj.fieldsets[0].properties[3].value; longitude = myobj.fieldsets[0].properties[4].value; // 直接创建对象,替代字符串拼接+JSON.parse的危险写法 locationString = { fieldsets: [{ alias: "weatherLocations", collapse: true, isValid: true, properties: [ { alias: "latitude", value: latitude, editorState: {}, isValid: true }, { alias: "useUsersLocation", value: useUsersLocation, editorState: {}, isValid: true }, { alias: "longitude", value: longitude, editorState: {}, isValid: true }, { alias: "cityName", value: cityName, editorState: {}, isValid: true }, { alias: "isoCode", value: isoCode, editorState: {}, isValid: true } ] }] }; // 在这里赋值,确保数据已准备完成 $scope.finalLocation = locationString; i++; }); }]);
额外说明
异步操作(比如API请求、Promise)的回调函数会在主线程任务全部完成后才执行,所以任何依赖异步结果的逻辑,都必须放在回调函数内部。
内容的提问来源于stack exchange,提问作者LAL1982
相关产品推荐
相关产品推荐

