Ember.js HTTP 400状态未命中路由事件挂钩
请点击此处: 我的应用程序对instagram进行ajax调用以获取用户的instagram提要,并在用户没有会话时重定向以进行身份验证。当Ember.js HTTP 400状态未命中路由事件挂钩,ember.js,Ember.js,请点击此处: 我的应用程序对instagram进行ajax调用以获取用户的instagram提要,并在用户没有会话时重定向以进行身份验证。当access\u令牌无效时,Instagram返回HTTP 400,我想根据400状态代码重定向。但是,当400响应从$.ajax()返回时,路由中的事件:钩子不会处理它。我在setupController()方法中有代码来处理它,但感觉不对 事件:是处理这些HTTP代码和放置重定向/转换逻辑的正确位置吗?如果是的话,你知道为什么它不起作用吗?如果没有,有没
access\u令牌
无效时,Instagram返回HTTP 400,我想根据400状态代码重定向。但是,当400响应从$.ajax()返回时,路由中的事件:
钩子不会处理它。我在setupController()
方法中有代码来处理它,但感觉不对
事件:
是处理这些HTTP代码和放置重定向/转换逻辑的正确位置吗?如果是的话,你知道为什么它不起作用吗?如果没有,有没有更好的方法来完成我想做的事情
App = Ember.Application.create();
App.Router.map(function() {
this.resource("instagram");
});
App.IndexRoute = Ember.Route.extend({
redirect: function() {
this.transitionTo('instagram');
}
});
App.InstagramRoute = Ember.Route.extend({
events: {
error: function(reason, transition) {
console.log('err. reason.status: ' + reason.status);
if (reason.status === 400) {
console.log('in evetns hook. Unauthorized, redirecting to: ' + App.Instagram.authURL);
this.transitionTo(App.Instagram.authURL);
} else {
console.log('err. reason.status: ' + reason.status);
}
}
},
setupController: function(controller) {
$.ajax({
url:"https://api.instagram.com/v1/users/1574083/?access_token=NO_TOKEN",
type:'GET',
dataType:'JSONP',
}).then(function(json){
if (json.meta.code ===400) {
console.log('in setupController ERROR 400: json: ' + JSON.stringify(json));
}
else {
controller.set('model', json.data);
}
});
}
});
App.Instagram = Em.Object.extend({
});
App.Instagram.reopenClass ({
authURL: 'https://instagram.com/oauth/authorize/?client_id=' + App.Instagram.clientId + '&redirect_uri=' + App.Instagram.redirectUri + '&response_type=token',
token: localStorage.Instagram_token,
tokenChanged: function() {
localStorage.token = this.get('Instagram_token');
}.observes('token')
});
更新:instagram web服务器返回HTTP 200,但响应JSON错误代码为400。因此我可以看到,
事件:
钩子可能不会触发,但在我的setupController()方法中处理所有4xx应用程序错误代码是否仍然正确?我建议这样做:
App.InstagramRoute = Ember.Route.extend({
events: {
error: function(reason, transition) {
console.log('err. code: ' + reason.code);
if (reason.code === 400) {
console.log('in evetns hook. Unauthorized, redirecting to: ' + App.Instagram.authURL);
this.transitionTo(App.Instagram.authURL);
} else {
console.log('err. reason.code: ' + reason.code);
}
}
},
model: function(params, transition) {
var promise = new Ember.RSVP.Promise(function(resolve, reject){
$.ajax({
url:"https://api.instagram.com/v1/users/1574083/?access_token=NO_TOKEN",
type:'GET',
dataType:'JSONP',
}).then(function(json){
if (json.meta.code ===400) {
console.log('ERROR 400: json: ' + JSON.stringify(json));
reject(json.meta);
}
else {
resolve(json.data);
}
});
})
return promise;
}
});
我不知道这段代码是否有效,但它可以给你一个提示。BINGO!你看到了我的目的,并把我带到了我想去的地方。我花了两天的时间试图让model:hook实现一个承诺,但无法实现,所以我决定使用setupController(),我认为这可能会破坏events:hook。很高兴知道我的直觉是正确的,但你的代码正是我想要实现的。我将深入研究RSVP,找出为什么它会起作用,但这太棒了,谢谢。
events
在Ember 1.0中被弃用。不要使用事件
而使用操作
。