javascriptangularjsroutesangularjs-ng-route

AngularJS $routeParams is undefiend, but property is there


angular.module("newsApp",["ngRoute"])
.config($routeProvider=>{
    $routeProvider.when("/edit",{
        templateUrl : "views/addNewsView.html"
    });
    $routeProvider.when("/newsList",{
        templateUrl : "views/newsList.html"
    });
    $routeProvider.when("/singleNews/:newsId",{
        templateUrl : "views/singleNews.html"
    });
    $routeProvider.when("/",{
        templateUrl : "views/newsList.html"
    });
    $routeProvider.otherwise({
        redirectTo:"/newsList"
    });
})

this is my module and config. i have simple app. i want to add functionality that when the user enters the url for example.com/singleNews/2 - it opens the news with ID - 2

.controller("newsAppCtrl",['$scope','$location','$routeParams',($scope, $location, $routeParams)=>{

    console.log($routeParams); //empty object

    setTimeout(function () {
        console.log($routeParams); //in this case property is there
    },100);

So when i enter the url

example.com/singleNews/2

the routeParams is empty object, although when i click to that empty object in chrome console the property is there and it says "value below was evaluated just now " but when i add that console into TimeOut, it works and property is there. I know that using setTimeOut() is not recommended in angularjs, so using $timeout solved the problem, but i want to understand what is the problem.


Solution

  • You should be getting an error in your console:

    Function.prototype.bind.apply(...) is not a constructor

    Simply avoid using (...)=>{...} syntax as AngularJS tried to call a function with new method() syntax and fails to do that with an arrow notation.

    Switch .config($routeProvider=>{...} to .config(function($routeProvider){...} (and other similar cases).

    Arrow notation can still be used and is useful with $http calls, e.g:

    $http.get(url).then( (res)=>{...} );