0

刷新浏览器后,我无法让我的一个页面保持空白。

当用户访问/user/:username时,profile.html加载。它在第一次加载时按预期工作,但如果我刷新页面,我会在屏幕上留下原始 JSON 输出(以前,它只会说“ null”)。

为了进一步了解,我的ng-href文件中有一个home.html

<h3>View your profile page <a ng-href="/user/{{user.username}}">here</a>.</h3>

对应的 Angular 文件:

var app = angular.module('social', ['ngRoute', 'ngCookies'])

app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
 templateUrl: 'home.html',
 controller: 'HomeController'
})
.when('/login', {
 templateUrl: 'login.html',
 controller: 'LoginController'
})
.when('/signup', {
 templateUrl: 'signup.html',
 controller: 'SignupController'
})
.when('/user/:username', {
    templateUrl: 'profile.html',
    controller: 'UserProfileController'
})
$locationProvider.html5Mode(true)

})

我的控制器:

app.controller('UserProfileController', function($http, $scope, $cookies, $rootScope, $routeParams) {
console.log("$cookies.get('currentUser')")
console.log($cookies.get('currentUser'))
function getCurrentUser() {
    $http.get('/user/' + $routeParams.username).then(function(res) {
        console.log('res.data in the user profile controller')
        console.log(res.data)
        $scope.user = res.data
    })
}

if ($cookies.get('currentUser') != undefined) {
    getCurrentUser()
} else {
    console.log("No one is here.")
}

})

我通过删除$locationProvider.html5Mode(true)和使用来实现ng-href="#/user/{{user.username}}"这一点,这意味着在页面刷新时不会丢失任何数据,并且我没有得到一个空白屏幕。但是,问题是#出现在 URL 中,这是我最终不想要的。显然,如果我将这样的应用程序投入生产,我不希望#出现在 URL 中。如果在开发过程中需要他们,我可以接受。

我还应该注意,我只有这个问题/user/:username。我的所有其他路由(//login/signup)都按预期工作,这意味着页面在刷新后不会变为空白,并且由于使用了 cookie,所有数据都会保留。

4

1 回答 1

1

AngularJS 将您的数据存储在内存中,因此当您刷新页面时,您将丢失数据,这就是您的页面留下原始表达式的原因,因为 angualr 丢失了绑定所需的数据。

您可以使用route resolves获取每个路由所需的数据,以便在刷新页面时,角度将调用该路由的解析函数,该函数会将数据返回给控制器。

路由在 Angular 中解析

于 2017-04-27T09:17:53.237 回答