解析允許你定義一組加載路線之前,將執行任務。只有一組鍵和功能是必不可少的,它們允許您在頁面加載之前執行諸如異步http請求,運行代碼片段,設置值等(真正需要的)。
因此,如果您有一個服務發出http請求並返回一個承諾,以確保每次發生路由時服務器上都存在一個會話,請解決該問題,直到完成http請求後才解決該問題,而這個承諾是成功的。換句話說,如果履行的承諾失敗,網頁將無法加載:
.config([ '$routeProvider', function($routeProvide) {
$routeProvider.when('/dashboard', {
templateUrl: 'framework/views/dashboard.html',
controller: 'DashboardCtrl',
controllerAs: 'dashCtrl',
resolve: {
DateOfBirth: ['Date', function(Date) { // random example of other uses for resolve
return Date.getCurrentYear() - 37;
}],
AuthUser: ['$q', '$location', 'UserSession',
function($q, $location, UserSession) {
return UserSession.getSession()
.then(function(success) { // server response 200 = OK
// if you are in here the promise has succeeded and
// the page will load
// can do whatever you want
return success
}, function(error) { // server response not 200 = Not OK
// if you are in here the promise has failed and
// the page will not load
// can do whatever you want
// if unauthenticated typically you'd:
$location.path('/login);
$location.replace();
// for this read up on promises, but promises can be
// chained, and it says move me to next error promise
// in the chain. if you don't use this it will assume
// the error was handled and pass you to the next
// success in chain. So good practice even if you're
// not chaining
return $q.reject(error);
});
}];
}
})
}]);
解決方案的另一個好處是鑰匙是可注射的。所以,你可以將結果傳遞給控制器:
.controller('DashboardCtrl', ['AuthUser', 'UserSession', 'DateOfBirth'
function(AuthUser, UserSession, DateOfBirth) {
// show all the errors you want by accessing the AuthUser
// data contained in the server response, or just read the
// server response status
var self = this;
self.status = AuthUser.status;
self.response = AuthUser.data;
}]);
然後在你的UI可以ngShow或使用dashCtrl.response或dashCtrl.status,或任何你與所解析數據做決定的結果ngBind等等等等,並知道從未加載頁面的錯誤。
我建議在路由上檢查會話,而不是將其存儲在客戶端。另外,請記住該解決方案僅適用於路由,但如果您打算調用不需要路由的服務器,則需要查看如何使用攔截器。它們允許您在與路由無關的傳出和傳入服務器請求/響應達到峯值,以便在當前處於特定頁面(例如/ dashboard/home)時發生的那些不會觸發路由的事件,只是簡單地更新/ home內容。
讓我知道如果某件事情沒有意義 – mtpultz 2014-10-09 17:08:58