简体   繁体   English

我应该如何将用户的登录状态传递给我的Ember.js应用程序?

[英]How should I pass user's login status to my Ember.js application?

I have an interactive Ember app which has a lot of options which are available only to signed in users. 我有一个交互式Ember应用程序,它有很多选项,只有登录用户才能使用。 For example there might be a list of posts, and then there's another link to my posts , which are relevant to the user. 例如,可能有一个帖子列表,然后是我的帖子的另一个链接,它与用户相关。

There are two issues that come to my mind: 我想到了两个问题:

  • how do I tell the app if a user is logged in, and maybe his data? 如何告诉应用程序用户是否已登录,以及他的数据?
  • how do I hide specific features and items based on his login state? 如何根据登录状态隐藏特定功能和项目?

Are there any best practices for approaching this? 是否有接近此问题的最佳做法? I guess the login process itself won't be that complicated, but the if logged_in? do_x else do_y 我想登录过程本身不会那么复杂,但if logged_in? do_x else do_y if logged_in? do_x else do_y is a big unknown for me atm. if logged_in? do_x else do_y对我来说是一个很大的未知数。 Where should I store the global user state? 我应该在哪里存储全局用户状态?

If you are using the ember router, then my suggestion would be to architect a solution like this 如果您正在使用ember路由器,那么我的建议是构建一个这样的解决方案

LoginController 的LoginController

App.LoginController = Ember.Controller.extend({
    login: function(params){ /* Your logic here */ },
    logout: function(params){ /* Your logic here */},

    user_data_hash: { first_name: "The", last_name: "Hobbit"},

    is_logged_in: (function() {
        /* do some logic and return true or false */
    }).property('some_item_on_user_data_hash')

    just_logged_in: (function() {
        /* do some logic and return true or false */
    }).property('some_item_on_user_data_hash')

Then in your router before you allow navigation to a protected route, you check with the LoginController object. 然后在允许导航到受保护路由之前在路由器中,使用LoginController对象进行检查。 This example is take from this answer . 这个例子来自这个答案

root: Ember.Route.extend({
    index: Ember.Route.extend({
        enter: function(router) {
            var logged_in = router.get('loginController.is_logged_in'); /*Or in older ember builds `router.getPath('loginController.is_logged_in');`*/
            var just_logged_in = router.get('loginController.just_logged_in'); /*Or in older ember builds `router.getPath('loginController.just_logged_in');`*/
            Ember.run.next(function() {
                if (logged_in && just_logged_in) {
                    router.transitionTo('loggedIn');
                } else if (!logged_in) {
                    router.transitionTo('loggedOut');
                }
            });
        }
    }),

    loggedIn: Ember.Route.extend({
        // ...
    }),

    loggedOut: Ember.Route.extend({
        // ...
    })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM