私は、続行するのに必要なすべての関連部品をフェッチする角度コントローラでセットアップ方法を呼びたいと思います。私は約束を使用すべきだと確信していますが、私は正しい使い方について少し混乱しています。
現在ログインしているユーザーをフェッチし、画面上に名前を表示し、顧客の詳細を取得して画面に表示する必要のあるShellControllerがあります。このシーケンスが失敗した場合は、失敗する箇所が1つ必要です。ここに私がこれまでに持っているものがあります(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'の中から返す値で解決される約束を返します。 –