Thursday 27 April 2017

Page goes blank after loading URL with $routeProvider in AngularJS

I'm having trouble from keeping one of my pages from going blank after refreshing my browser.

When a user visits /user/:username, profile.html loads. It works as intended on the first load, but if I refresh the page, I'm left with a raw JSON output on the screen (previously, it would just say "null").

For further context, I have an ng-href in my home.html file:

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

The corresponding Angular file:

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)

})

My controller:

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.")
}

})

I got this to work by removing $locationProvider.html5Mode(true), and using ng-href="#/user/", meaning that no data is lost upon page refresh, and I don't get a blank screen. But, the problem is that the # shows up in the URL, which I eventually won't want. Obviously, if I push an app like this to production, I don't want the # appearing in the URL. If it needs to be their during development, I can live with that.

I should also note that I only have this problem with /user/:username. All of my other routes (/, /login, and /signup) work as expected, meaning the pages don't go blank after a refresh, and all the data persists due to the use of cookies.



via Farid

No comments:

Post a Comment