gpt4 book ai didi

javascript - Angular 等待变量已定义

转载 作者:行者123 更新时间:2023-11-28 06:22:32 25 4
gpt4 key购买 nike

我有 2 个 Controller 和一项服务:

angular.module('objDescApp', ['ui.router', 'ui.bootstrap']);
angular.module('objDescApp').config(['$stateProvider', '$urlRouterProvider', '$httpProvider', function ($stateProvider, $urlRouterProvider, $httpProvider) {
'use strict';
$urlRouterProvider.otherwise('/');

$stateProvider
.state('object', {
url: '/{name}',
views: {
"body": {
controller: 'ObjectDetailCtrl',
template: '...'
}
});


angular.module('objDescApp').controller('ObjectListCtrl', function ($scope, $state, ConfigService) {
ConfigService.getConfig(function(){//get config from server
$scope.object = ConfigService.fillConfigForObjList(); //use config
}
}

angular.module('objDescApp').controller('ObjectDetailCtrl', ['$scope', '$stateParams', 'ConfigService', function ($scope, $stateParams, ConfigService) {
$scope.current_object = ConfigService.fillConfigForObjDetail(); //use config
}

angular.module('objDescApp').factory('ConfigService', function ($http, $rootScope) {
var jsonConf;
var confTemplate = {"sometemplate" : {}};

function fillConfigForObjList (){
... //use jsonConf variable , and always wait for init because of called only inside callback function of getConfig();
};
function fillConfigForObjDetail(){
... //use jsonConf variable , but doesnt wait for jsonConf initialization, so error var 'is undefined' here.So I need to add some waiting for 'jsonConf' initialization logic here

};

return {
jsonConf: jsonConf,
fillConfigForObjDetail: fillConfigForObjDetail,
fillConfigForObjList: fillConfigForObjList,
getConfig: function(callback){
$http({
method: 'GET',
url: endPointUrl,
transformResponse: undefined
}).then(
function successCallback(response) {
jsonConf = JSON.parse(response.data);
$rootScope.getConfigError = false;
callback();
},
function errorCallback(response) {
if(response.status == "404"){
jsonConf = confTemplate;
}else{
console.log("Get config error");
jsonConf = confTemplate;
$rootScope.getConfigError = true;
}
callback();
}
);
}
}

因此,当我使用主路径 '/' 加载页面时,一切正常,因为“ObjectListCtrl” Controller 触发 getConfig() 函数它在响应后设置 'jsonConf' 变量,因此我可以在任何状态之间导航,并且一切正常,因为 'jsonConf' 已设置;

但是如果我以 '/{name}' 等起始路径状态重新加载页面,那么“ObjectListCtrl” Controller 会触发“'getConfig()” 向服务器发出请求,但以异步方式触发 'ObjectDetailCtrl' Controller 及其 $scope.current_object = ConfigService.fillConfigForObjDetail() 表达式,该表达式会抛出 jsonConf 是未定义错误;那么有人可以告诉我如何在 'fillConfigForObjDetail()' 函数内等待,直到通过 getConfig() 函数初始化 'jsonConf' 变量。

最佳答案

保存 promise 并从 promise 中

   var jsonConfPromise;

function getConfig() {
//save httpPromise
jsonConfPromise = $http({
method: 'GET',
url: endPointUrl,
transformResponse: undefined
}).then(
function successCallback(response) {
jsonConf = JSON.parse(response.data);
$rootScope.getConfigError = false;
//return for chaining
return jsonConf;
},
function errorCallback(response) {
if(response.status == "404"){
jsonConf = confTemplate;
}else{
console.log("Get config error");
jsonConf = confTemplate;
$rootScope.getConfigError = true;
}
//return for chaining
return jsonConf;
}
);
//return promise
return jsonConfPromise;
};

有问题的函数可以链接 promise 。

function fillConfigForObjDetail(){
/*
... //use jsonConf variable , but doesnt wait for jsonConf
initialization, so error var 'is undefined' here.
So I need to add some waiting for 'jsonConf' initialization
logic here
*/

//chain from the promise
jsonConfPromise.then(function (jsonConf) {
//use resolved jsonConf
});
};

也在您的 Controller 中,而不是使用回调,来自返回的 promise 。

angular.module('objDescApp').controller('ObjectListCtrl', function ($scope, $state, ConfigService) {
var configPromise = ConfigService.getConfig();
configPromise.then(function() {
$scope.object = ConfigService.fillConfigForObjList();
});
});

AngularJS 框架使用 promise 而不是回调

有关链式 promise 的更多信息,请参阅 AngularJS $q Service API Reference -- chaining promises .

Because calling the then method of a promise returns a new derived promise, it is easily possible to create a chain of promises. It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain. This makes it possible to implement powerful APIs.1

关于javascript - Angular 等待变量已定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35386891/

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