user4251615
user4251615

Reputation:

Why is $routeParams not working? Undefined

I'm triyng to build simple applications on Angular and Django rest framework. I have a next root app: app.js

angular
    .module('sharePhotoApp', [
    'ngRoute',
    'sharePhotoApp.controllers',
    'sharePhotoApp.services'
    ])
    .config(['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/', {
          templateUrl: '/',
          controller: 'PostListController'
        })
        .when('/:username', {
          templateUrl: '/user/',
          controller: 'UserDetailController'
         })
        .otherwise({
          redirectTo: '/'
        });
}]);

And the next controller:

angular
    .module('sharePhotoApp.controllers')
    .controller('UserDetailController',  UserDetailController)

    UserDetailController.$inject = ['$scope','$routeParams','userService'];

function UserDetailController($scope, $routeParams, userService){

    alert($routeParams.username);

    $scope.user = userService.get({ username: $routeParams.username });
}

I tried to follow the next URL in browser: http://127.0.0.1:8000/user/#/admin I suppose in this case should triggered route with username parameter. But I've gotten undefined. Could anyone explain where I done mistake?

Upvotes: 0

Views: 886

Answers (1)

Eigi
Eigi

Reputation: 716

"Note that the $routeParams are only updated after a route change completes successfully. This means that you cannot rely on $routeParams being correct in route resolve functions. Instead you can use $route.current.params to access the new route's parameters."

https://docs.angularjs.org/api/ngRoute/service/$routeParams

Have you also installed ngRoute module?

As the description says, the route is not finished in your controller, so the params are also undefined.

$scope.$on('$routeChangeSuccess', function() {
    // $routeParams should be populated here
  });

should do the work.

Upvotes: 1

Related Questions