我想在角度控制器中調用setup方法,該角度控制器獲取所需的所有相關組件部分以繼續。我確信我應該使用promise,但是我對正確的用法有點困惑。考慮到這一點:
我有一個ShellController,需要獲取當前登錄的用戶,然後在屏幕上顯示他們的名字,然後獲取一些客戶的詳細信息,並將其顯示在屏幕上。如果在任何時候這個序列都失敗了,那麼我需要一個地方讓它失敗。這是我到目前爲止(不工作ofc)。
var app = angular.module('app', [])
app.controller('ShellController', function($q, ShellService) {
var shell = this;
shell.busy = true;
shell.error = false;
activate();
function activate() {
var init = $q.when()
.then(ShellService.getUser())
.then(setupUser(result)) //result is empty
.then(ShellService.getCustomer())
.then(setupCustomer(result)) // result is empty
.catch(function(error) { // common catch for any errors with the above
shell.error = true;
shell.errorMessage = error;
})
.finally(function() {
shell.busy = false;
});
}
function setupUser(user) {
shell.username = user;
}
function setupCustomer(customer) {
shell.customer = customer;
}
});
app.service('ShellService', function($q, $timeout) {
return {
getUser: function() {
var deferred = $q.defer();
$timeout(function() {
deferred.resolve('User McUserface');
}, 2000);
return deferred.promise;
},
getCustomer: function() {
var deferred = $q.defer();
$timeout(function() {
deferred.resolve('Mary Smith');
}, 2000);
return deferred.promise;
}
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="ShellController as shell">
<div class="alert alert-danger" ng-show="shell.error">
An error occurred! {{ shell.errorMessage }}
</div>
<div class="alert alert-info" ng-show="shell.busy">
Fetching details...
</div>
<div>Username: {{ shell.username }}</div>
<div>Customer: {{ shell.customer }}</div>
</div>
</body>
,我應該怎麼做嗎?
'then'函數返回一個承諾,將用你將從'then'返回的值來解析,例如'.then(function(){return 1})。then(function(value){console.log(value); // 1});' –