[英]How to transition to a route from an Ember Data Adapter
在我的應用程序中,我有一個ApplicationAdapter
其ajaxError
方法是自定義的。 在該方法中,我希望能夠轉換到給定的路線 。 我怎樣才能做到這一點?
App.ApplicationAdapter = DS.RESTAdapter.extend({
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR) {
switch(jqXHR.status) {
// [...]
case 401:
// How can I transitionTo('login') here?
}
// [...]
}
}
});
而不是適配器中的轉換,不是一個好的實踐恕我直言,您可以返回Error
的實例並在當前路由的error
操作中處理它:
App.UnauthorizedError // create a custom Error class
App.ApplicationAdapter = DS.RESTAdapter.extend({
ajaxError: function(jqXHR) {
var defaultAjaxError = this._super(jqXHR);
if (jqXHR) {
switch(jqXHR.status) {
case 401:
return new App.UnauthorizedError()
}
}
return defaultAjaxError;
}
});
App.IndexRoute = Ember.Route.extend({
model: function() {
return this.store.find('person');
},
actions: {
error: function(reason) {
// all errors will be propagated to here, we check the instance to handle the UnauthorizedError
if (reason instanceof App.UnauthorizedError) {
this.transitionTo('login')
}
}
}
});
如果要將其用於所有路由,可以將未經授權的轉換放在ApplicationRoute
。 由於ApplicationRoute是所有路由的父級,而不是處理的操作或返回true的操作,因此將冒泡到父路由。
App.ApplicationRoute = Ember.Route.extend({
actions: {
error: function(reason) {
if (reason instanceof App.UnauthorizedError) {
this.transitionTo('login')
}
}
}
});
App.BarRoute = Ember.Route.extend({
actions: {
error: function(reason) {
// handle errors of bar route
// bubble to application route
return true;
}
}
});
這是這個樣本http://jsfiddle.net/SkCH5/的小提琴
拋出錯誤並允許路由上的錯誤掛鈎捕獲它並從那里轉換。 此外,您可以使用此邏輯進行混音,並將mixin添加到您的所有路線中。
Machty在他的要點中有關於新路由器的更多信息: https ://gist.github.com/machty/5647589
App.AuthenticatedRoute = Ember.Route.extend({
beforeModel: function(transition) {
if (!authTokenPresent) {
return RSVP.reject();
// Could also just throw an error here too...
// it'll do the same thing as returning a rejecting promise.
// Note that we could put the redirecting `transitionTo`
// in here, but it's a better pattern to put this logic
// into `error` so that errors with resolving the model
// (say, the server tells us the auth token expired)
// can also get handled by the same redirect-to-login logic.
}
},
error: function(reason, transition) {
// This hook will be called for any errors / rejected promises
// from any of the other hooks or provided transitionTo promises.
// Redirect to `login` but save the attempted Transition
var loginController = this.controllerFor('login')
loginController.set('afterLoginTransition', transition);
this.transitionTo('login');
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.