刷新浏览器后,我无法让我的一个页面保持空白。
当用户访问/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,所有数据都会保留。