gpt4 book ai didi

javascript - AngularJS工厂函数添加promise

转载 作者:行者123 更新时间:2023-11-28 14:40:44 24 4
gpt4 key购买 nike

我正在 Angular 工厂内创建一个函数。我需要这个函数返回 promise 。然后我添加其他功能。

    SPApp.factory('processing', ['$http', '$rootScope', '$q', function ($http, $rootScope) {
function initialize($scope, status) {


$http({
method: 'GET',
url: '/api/ApiCustomer/GetCustomerDetails'

}).then(function (data) {
if (data.data.ModelValue == null) {
$rootScope.redirectToLogin();
} else {
$scope.CustomerInformation = data.data.ModelValue;


}
}).then(function () {
$http({
method: 'GET',
url: '/api/ApiList/AccountTypeList'
}).success(function (result) {
$scope.accountTypeList = result;
typeOfAccount = result;
});

// get currncy list

$http({
method: 'GET',
url: '/api/ApiList/CurrencyList'
}).success(function (result) {
$scope.currencyList = result;

//jQuery('#ProfileImage').attr('src', "/Content/Images/blank-avatar.jpg");
});


$http({
method: 'GET',
url: '/api/ApiList/BankListByUserType',
}).success(function (result) {
$scope.bankList = result;
});

});

};

return {
initialize: initialize
}
}]);

以及如何将此函数作为 Promise 调用并使用 then

processing.initialize($scope, true).then(function(){
console.log("hello world");
});

现在不行了,如果您知道流程,请帮忙

最佳答案

您应该从工厂返回Promise

SPApp.factory('processing', ['$http', '$rootScope', '$q',   function ($http, $rootScope, $q) {
function initialize($scope, status) {
return $http({
method: 'GET',
url: '/api/ApiCustomer/GetCustomerDetails'
});
}

return {
initialize: initialize
}
}
]);

在 Controller 方法中使用输出

processing.initialize($scope, true).then(function (data) {
$scope.basicInfo = data.data.ModelValue.PersonalInformations[0];
});
<小时/>

根据评论初始化函数有多个http请求,您可以使用$q.all()方法来等待所有的 promise 来完成。

SPApp.factory('processing', ['$http', '$rootScope', '$q', function ($http, $rootScope, $q) {
function initialize($scope, status) {
var returnData = {},
var a = $http({
method: 'GET',
url: '/api/ApiCustomer/GetCustomerDetails'
}).then(function (response) {
returnData.basicInfo = response.data.ModelValue.PersonalInformations[0];
});

var b = $http({
method: 'GET',
url: '/api/ApiList/AccountTypeList'
}).then(function (response) {
returnData.accountTypeList = response;
});

return $q.all([a, b]).then(function () {
return returnData;
});
}

return {
initialize: initialize
}
}
]);

关于javascript - AngularJS工厂函数添加promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48168445/

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