在硬刷新,$ rootScope消失,不能访问当前用户 [英] On hard refresh, $rootScope disappears and cannot access current user

查看:1769
本文介绍了在硬刷新,$ rootScope消失,不能访问当前用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 $ rootScope 始终可以访问登录的用户的电流。当用户提交一个新的餐到系统中的一顿属性存储加上提交谁它们的用户ID。

这工作,但现在我很难刷新我的浏览器中, $ rootScope.user 对象消失。

我如何prevent呢?

app.js 我有:

$ rootScope.user;

下面是当用户登录时会发生什么:

 验证。$ onAuth(功能(用户){
                如果(用户=== NULL){
                    的console.log(未登录尚);
                }其他{
                    的console.log(被当作,user.uid);
                }
                $ rootScope.user =用户;
        });

然后,当用户访问AddMeal页,在 AddCtrl 我们有:

  VAR firebaseObj =新的火力地堡(https://myapp.firebaseio.com/courses/);
    变种FB = $ firebaseArray(firebaseObj);
的console.log($ rootScope.user)$ scope.newMeal = {
    名称: ,
    价钱: ,
    配料: ,
    说明:,
    类别:,
    美食:,
    用户帐号:
};$ scope.submitMeal =功能(){
    如果(angular.equals({},$ scope.newMeal)){
        警报(你的表格是空);
        $ rootScope.notify(你的表格是空')
    }其他{
        的console.log($ scope.newMeal);
        变量名称= $ scope.newMeal.name;
        VAR价格= $ scope.newMeal.price;
        VAR成分= $ scope.newMeal.ingredients;
        Var描述= $ scope.newMeal.description;
        VAR类别= $ scope.newMeal.category;
        VAR美食= $ scope.newMeal.cuisine;        FB。$加({
            名称:姓名,
            价格:价格,
            成分:配料,
            说明:说明,
            类别:类别,
            美食:美食,
            用户名:$ rootScope.user.uid
        }),然后(功能(REF){
            $ scope.newMeal = {};
            的console.log(REF);
        },功能(错误){
            的console.log(错误,错误);
        });        $ rootScope.notify(新饭已添加!)
    }

下面是我的运行函数 app.js

  .RUN(函数($ ionicPlatform,$ rootScope,$ firebaseAuth,$火力点,$窗口,$ ionicLoading){
        $ ionicPlatform.ready(函数(){
            //默认隐藏附件栏(删除此显示键盘上方的附件栏
            //表单输入)
            如果(window.cordova&安培;&安培; window.cordova.plugins.Keyboard){
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(真);
                cordova.plugins.Keyboard.disableScroll(真);            }
            如果(window.StatusBar){
                // org.apache.cordova.statusbar要求
                StatusBar.styleDefault();
            }            $ rootScope.show =功能(文字){
                $ rootScope.loading = $ ionicLoading.show({
                    内容:文字?文本:加载中...',
                    动画:'淡入',
                    showBackdrop:真实,
                    了maxWidth:200,
                    showDelay:0
                });
            };            $ rootScope.hide =功能(){
                $ ionicLoading.hide();
            };            $ rootScope.notify =功能(文字){
                $ rootScope.show(文本);
                $ window.setTimeout(函数(){
                    $ rootScope.hide();
                },1999);
            };            $ rootScope.user;        });
    })


解决方案

AngularJS工程作为SP​​A(这里你可以阅读一些关于它)。问题的关键是,当页面重新加载,因为任何其他的SPA,它就会失去所有的数据和应用程序将是reeboted。这就是为什么你得到了这个问题。

有一个简单的方法来解决这个问题:
当应用程序加载/重载,它会转到的app.config()和分辩后它去了 app.run()(如果有的话)。
所以,我对你的解决办法是保持在localStorage的用户的信息数据(像一个cookie中),然后从那里要求它时,应用程序初始化。

  angular.module('MyApp的')。运行(函数($ rootScope){
    如果(angular.isDefined($ rootScope.userInfo)及!&放大器; localstorage.userInfo){
        //的UserInfo存在于localstorate但不能在$ rootScope。这意味着页面重新加载了,或者用户正在恢复。
        $ rootScope.userInfo = localstorage.userInfo;
    }否则如果(angular.isDefined($ rootScope.userInfo)及!&放大器;!localstorage.userInfo){
        //用户是不是在所有的记录。把他送回登录页面
    }否则如果(angular.isDefined($ rootScope.userInfo)){
        //用户已登录。你可以这里运行一些额外的验证。
    }
});

我假设你把你的用户信息在一个变量 $ rootScope.userInfo

这已经说了,我强烈建议你尝试服务,让您的数据,而不是在$ rootScope。 这里指导你如何能做到这一点。

我希望这能解决您的问题。

**更新

如果你使用离子的工作,你可以尝试这样的事:

  VAR对myApp = angular.module('对myApp',['离子']);
    myApp.run(函数($ ionicPlatform){
        $ ionicPlatform.ready(函数(){
        //将localStorage的或DB你保存设置。
    });
});

此<一个把它href=\"http://stackoverflow.com/questions/29469291/ionic-application-startup-event\">reference.

I am using $rootScope to always access the current logged in user. When the user submits a new meal into the system the meal attributes are stored plus the user id who submitted them.

This works, but the moment I hard refresh my browser, the $rootScope.user object disappears.

How do I prevent that?

In app.js I have:

$rootScope.user;

Here's what happens when the user logs in:

Auth.$onAuth(function (user) {
                if (user === null) {
                    console.log("Not logged in yet");
                } else {
                    console.log("Logged in as", user.uid);
                }
                $rootScope.user = user;
        });

Then, when the user accesses the AddMeal page, within the AddCtrl we have:

var firebaseObj = new Firebase("https://myapp.firebaseio.com/courses/");
    var fb = $firebaseArray(firebaseObj);
console.log($rootScope.user)

$scope.newMeal = {
    name: "",
    price: "",
    ingredients: "",
    description: "",
    category: "",
    cuisine: "",
    userID:""
};

$scope.submitMeal = function () {
    if (angular.equals({}, $scope.newMeal)) {
        alert("Your form is empty");
        $rootScope.notify('Your form is empty')
    } else {
        console.log($scope.newMeal);
        var name = $scope.newMeal.name;
        var price =  $scope.newMeal.price;
        var ingredients= $scope.newMeal.ingredients;
        var description = $scope.newMeal.description;
        var category= $scope.newMeal.category;
        var cuisine= $scope.newMeal.cuisine;

        fb.$add({
            name: name,
            price: price,
            ingredients: ingredients,
            description: description,
            category: category,
            cuisine: cuisine,
            userID: $rootScope.user.uid
        }).then(function(ref) {
            $scope.newMeal = {};
            console.log(ref);
        }, function(error) {
            console.log("Error:", error);
        });

        $rootScope.notify('New meal has been added!')
    }

Here is my run function in app.js:

.run(function ($ionicPlatform, $rootScope, $firebaseAuth, $firebase, $window, $ionicLoading) {
        $ionicPlatform.ready(function () {
            // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
            // for form inputs)
            if (window.cordova && window.cordova.plugins.Keyboard) {
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
                cordova.plugins.Keyboard.disableScroll(true);

            }
            if (window.StatusBar) {
                // org.apache.cordova.statusbar required
                StatusBar.styleDefault();
            }

            $rootScope.show = function(text) {
                $rootScope.loading = $ionicLoading.show({
                    content: text ? text : 'Loading..',
                    animation: 'fade-in',
                    showBackdrop: true,
                    maxWidth: 200,
                    showDelay: 0
                });
            };

            $rootScope.hide = function() {
                $ionicLoading.hide();
            };

            $rootScope.notify = function(text) {
                $rootScope.show(text);
                $window.setTimeout(function() {
                    $rootScope.hide();
                }, 1999);
            };

            $rootScope.user;

        });
    })

解决方案

AngularJS works as a SPA (here you can read a bit about it). The point is that when the page reloads, as any other SPA, it will lose all its data and the app will be "reeboted". This is why you are getting this problem.

There's an easy way to solve it: When the app loads/reloads, it goes to the app.config() and rigth after that it goes to the app.run() (if any). So my solution for you is to keep your user's info data on the localstorage (works like a cookie) and then ask for it from there when the app initialize.

angular.module('MyApp').run(function($rootScope){
    if(!angular.isDefined($rootScope.userInfo) && localstorage.userInfo){
        // UserInfo exists in localstorate but not on $rootScope. This means the page was reloaded or the user is returning.
        $rootScope.userInfo = localstorage.userInfo;
    }else if(!angular.isDefined($rootScope.userInfo) && !localstorage.userInfo){
        // User is not logged at all. Send him back to login page
    }else if(angular.isDefined($rootScope.userInfo)){
        // User is logged in. You can run some extra validations in here.
    }
});

I'm assuming you keep your users info on a variable $rootScope.userInfo

That been said, I strongly recommend you try a Service to keep your data rather than on the $rootScope. Here's a guide on how you can achieve that.

I hope this solves your issue.

**UPDATE

If you're working with Ionic you can try something like this:

var myApp = angular.module('myApp', ['ionic']);
    myApp.run(function($ionicPlatform) {
        $ionicPlatform.ready(function() {
        //load your settings from localStorage or DB where you saved.
    });
});

Took it from this reference.

这篇关于在硬刷新,$ rootScope消失,不能访问当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆